# Question
Title: Getting the tile over wich the mouse cursor is
Im making a tilebased game, I have the rendering, the main engine, everything setup nicely (btw Im using LWJGL and Slick). Now this is more of a math question. How do I get the tile the mouse is on, so that I can draw a rectangle around that tile, so that I can later do stuff with that tile (e.g. if its stone Ill break it if I click...) I draw the map at an offset so the player is always in the middle of the screen, the upper left corner coordinates Ive called xot and yot, the offsets xOff and yOff, and yea. If anyone knows what math I need to use to get the propper tile x and y.

# Answer
Converting mouse coordinates into tiles coordinates is quite simple, as long as you know the width and height of your tiles. All you need to do is, converting mouse coordinates into world coordinates, then performing simple math to get the indexes of the tile the cursor in lying on. Let's have an example.

### A small grid

We have an 8x8 grid consisting of 32x32-pixel tiles:

Be careful when dealing with coordinates: the horizontal and vertical lines are still part of a given tile, as follows:

So, *(0,0)* is our world origin. Such a tile ends at *(31,31)*, whilst any other multiple of 32 is the upper-left corner of a new tile. In the figure above, the coordinates *(64,32)* are mapped to the tile at position *\[2,1\]* in our grid. If we consider *(63,32)* we are instead moving to tile *\[1,1\]*. And so on.

### Getting coordinates

Based on the previous, we want our cursor to map the tile at position *\[3,5\]* in our grid. Such an algorithm must convert mouse coordinates on the screen into world coordinates, and we do this by considering the current camera (or view) position in the world, and sum these values to the mouse coordinates (I'm using sort of pseudo-code):

```
// Convert mouse screen coords into world coords
var mouse_x = get_mouse_x();
var mouse_y = get_mouse_y();

mouse_x += camera_offset_x;
mouse_y += camera_offset_y;

```

At this point, your `mouse_x` and `mouse_y` variables are both holding the absolute coordinates in your world. A graphical explanation of this follows:

In our example, the mouse is at position *(60,46)* on the screen, and the current view is located at *(64,128)*. So, doing the math, at the end it will results:

> `mouse_x = 124;` `mouse_y = 174;`

Right as it was in the very first picture.

### Mapping tiles

Now, let's convert mouse coordinates in the world into tiles indexes in our grid. We want our *x* coordinates to refer to column 0 when *x* value is between 0 and 31 (included), column 1 when its value is between 32 and 63 (included), and so on. Same story for *y* coordinates related to the index of rows. Then, we divide the current coordinate with the width of a tile - getting a ratio value - and finally we round it to the lowest integer to get the index for each axis:

```
// Get tile index from world coordinates
var tile_u = 0;
var tile_v = 0;

tile_u = floor(mouse_x/TILE_WIDTH);
tile_v = floor(mouse_y/TILE_HEIGHT);

```

How does this work? Our `mouse_x` and `mouse_y` variables were holding the mouse position in the world after the first part: *(124,174)*. The math happened here was, for *x* axis:

> `tile_u = floor(124/32) = floor(3.875) = 3;` `tile_v = floor(174/32) = floor(5.4375) = 5;`

Aaand here are the indexes of the tile the mouse is on:

Hope that helps.
> 1 votes

# Answer
If you have the coordinates of the mouse in pixels, the offset of the camera in pixels, and the size of the tiles in pixels, you just add the camera offset to the mouse coords, then devide by the size of tiles. Let's say `camera_offset == 60`, `mouse_position == 85` and `tile_size == 10`. Then `(camera_offset + mouse_position) / tile_size == 14.5` or tile 15.
> 0 votes

---
Tags: java, mathematics, lwjgl, slick
---


title: Render ModelContent directly

text:
# Question
Title: Render ModelContent directly
Say I have a set of `.fbx` files which contain all my bones, meshes and animations. I want to make use of these in the finished application i.e. rather than converting them all to `.xnb` I just want to load the `.fbx` files at runtime. I've got `AssImp` importing them, `MonoGame.Framework.Content.Pipeline` processing them, but now I have a `ModelContent` object which is not usable as a `Model` (unless I'm missing something obvious).

Can I convert these to `Model` without passing them to a `ContentWriter`/`ContentReader`?

# Answer
MonoGame does not support that, and original XNA did not either (as XNA developer Shawn Hargreaves blogged, "you must either use the Content Pipeline, or not use the type at all"). `ModelContent` gets serialized to the XNB file, and the file is deserialized to a `Model` by the framework.

This is because a runtime dependency to the Content Pipeline assemblies would be useless bloat for most applications (and in XNA's case, a licensing nightmare). XNB is a fast runtime format containing only the necessary data, whereas FBX is the exact opposite. If you *really* need to use FBX models, you have to modify or reimplement `Model`/`ModelContent`.
> 2 votes

---
Tags: monogame, xna-content-pipeline
---


title: MonoGame Gamepad Y axis flipped?

text:
# Question
Title: MonoGame Gamepad Y axis flipped?
I'm following a book I bought on Google Play that is teaching me the ropes of MonoGame, and in Chapter 2 it introduces creating an input wrapper that takes care of all the input methods for a game pad or keyboard. What's supposed to happen is that the WASD keys is mapped to the same inputs that the right thumb-stick would be on the game pad, but what happens for me is that the WASD keys move up and down correctly, but on the game pad it is flipped for some reason. I've looked over every line that I think would cause the problem, even replacing my code with the source code in the book, and the project they provide as an example works perfectly, but my project using THEIR code does not. If anyone can look over my project and see what the problem could be, that would be awesome!

Project: Here

MonoGame Book (Would Recommend So Far): Here

# Answer
> 0 votes
On a thumbstick Y positive 1 means "up":

```
if (GamePad.GetState( PlayerIndex.One ).ThumbSticks.Left.Y == 1.0f)
{
// Player one has pressed the left thumbstick up.
}

```

See Documentation for thumbstick on MSDN (note Monogame is a implementation of XNA):

> Each of the thumbstick axis members is a signed value describing the position of the thumbstick. A value of 0 is centered. Negative values signify down or to the left. Positive values signify up or to the right. The controller typically does not generate thumbstick values within a dead zone, or marginal input region around the center position.

In your code `private Vector2 ThumbStickState(Vector2 thumbStickValue, Keys up, Keys down, Keys left, Keys right)` you state (comments mine):

```
        Vector2 r = new Vector2(0f, 0f);
        if ((GamePad.GetState(PlayerIndex.One).IsConnected))
        {
            r = thumbStickValue; //uses the thumbstick value returned by Monogame.
        }
        if (Keyboard.GetState().IsKeyDown(up))
            r.Y -= kKeyDownValue; //note the -=

```

Thus from your code, the keypress indicates a negative Y for up, while the thumbstick returns a positve 1 for up. Your code is working as specified (perhaps not as you expected).

I can't comment on the code from the book as I don't have it.

# Answer
> 0 votes
Screen coordinates differ from thumbstick direction and other vector types in that Y increases *down*. In your case, negating the GamePad Y value makes it match the screen coordinate system. (In a 3D project the projection matrix would fix it.)

---
Tags: c#, xna, xna-4.0, monogame, visual-studio
---


# Question
Title: Unity rope/cable physics / anchor points
I'm creating a cable in Unity, which should behave realistically. I found 2 different ways to approach the problem.

First was to simply rigg a subdivided cylinder in Blender, Cinema4D or whatever editor you like and you set up hinge joints between the bones in Unity.

Second approach was to apply a Cloth Component in Unity. I tried the second approach with the cloth component. The physics work nice, but I don't know, how to make anchor points for the cloth object. I'm just able to add colliders, but the object is slipping away pretty fast from them.

So my first question is, which approach has the most benefits above the other and which benefits do they have. Second question, how can I create anchor points for my cloth object.

# Answer
Use physics joints in bones of cable/rope model. You will get better physical result. Use configurable joint for more control.

We used same method to tank crawler and wheel.

Using cloth physics seems not related in your case.
> 1 votes

---
Tags: physics, unity, rope-physics
---


# Question
Title: Should I use one GLSurfaceView.Renderer for each part of my game?
I am creating a small platformer-like game for Android using OpenGL. The game has 3 main screens/states:

1. Main menu screen
2. Level selection screen
3. The game screen

Currently I use a GLSurfaceView.Renderer to render all three screens and just run different parts of the render code depending on which screen I am on. Now my code is getting really messy because the render(), update() and onTouchEvent() methods of the renderer all have code for all three states in big if statements.

My question is now: Is it possible to have multiple GLSurfaceView.Renderer's (one for each screen/game state) and how can I implement the switching between them?

# Answer
It's probably better to use *one* surface view. Each `GLSurfaceView` appears to get its own OpenGL context unless you jump through a bunch of hoops to manually create the context and customize the way each surface creates its context.

The practical upshot is that you cannot easily share resources between each view, so you will need to reload textures and geometry or keep two copies of them in memory at all times. This will have a negative impact on performance, memory use, or both depending on precisely how you implement it.

Using a single view avoids these problems. To alleviate your messy code issues, consider instead building a more robust state management system.

A very classical, straightforward approach to doing so is creating a `GameState` base class with virtual `update`, `render` and `handleTouch` calls. Then create three child classes, one for each of your current game states, and isolate your rendering and logic for each state to each state's appropriate overridden methods. Your primary view simply holds a reference to the active state and calls that state's render/update/whatever calls as needed. When you transition between states you just switch out what this reference points to.
> 2 votes

# Answer
The docs for `setRenderer()` say:

> This method should be called once and only once in the life-cycle of a GLSurfaceView.

If you look at the source code, you'll find that they actually meant "must" rather than "should". The `setRenderer()` method checks to see if a render thread is running. If not, it creates one and starts it. If the thread already exists, the call fails.

So you can't change out your GLSurfaceView.Renderer object. Switching based on game current state is the preferred approach.
> 1 votes

---
Tags: opengl, android, opengl-es
---


title: Calculate camera target

text:
# Question
Title: Calculate camera target
How calculate camera target position, if I have front/back planes, camera transformation matrix and camera lens length?

# Answer
You can't.

This is assuming that you have used the following function

```
void gluLookAt(GLdouble eyeX,
  GLdouble eyeY,
  GLdouble eyeZ,
  GLdouble centerX,
  GLdouble centerY,
  GLdouble centerZ,
  GLdouble upX,
  GLdouble upY,
  GLdouble upZ);

```

to get your transformation matrix, and that you want to find what values were used for `center` parameters.

The lookat method will give you a matrix that is good to transform the camera position, but will use 'clean' values for it: it will at least normalize the center-eye vector.

If you want to keep track of what is the 'center' of the camera, keep it in a variable, and use that variable instead.

(Doc)
> 1 votes

---
Tags: camera, projection-matrix
---


# Question
Title: Weapon RPS - circular list; troubles keeping circular list balanced when expanding
I've got a idea for a game in the works, and I'm trying to figure out how to sort 17 weapons into a circular list where each weapon beats the 8 below it but loses to the 8 above it. Currently, I only have an RPS-5 figured out where each beats the 2 below it but loses to the 2 above it:

* bow
* daggers
* magical orb
* gun
* glaive

I then set out to try to expand it into an RPS-7, starting by adding one weapon and creating a placeholder spot to find the most appropriate weapon for. I came up with "spear", which I determined beats "magical orb" and "glaive" but loses to "bow", "daggers", and "gun". What with "gun" being smack between the two things that "spear" beats though, where do I put the placeholder spot? I'm assuming if it's even possible without giving up on my well thought reasons for why what beats what I'll need more than 1 placeholder spot to find an appropriate weapon for.

Is it at all possible to place the placeholder spots such that "spear" ends up above "magical orb" and "glaive" while still being below "bow", "daggers", and "gun"? Or will I have to either alter an interaction or see if I can create a perfectly imbalanced RPS?

If this question would benefit from additional tags, please let me know.

# Answer
You can't have a single list that satisfies the conditions you want. One option is to reconsider your weapon types such that the new one you add between daggers and magical orb actually beats magical orb, gun, and glaive and loses to bow and daggers.

Otherwise if you want more complex pairings then a simple list is not the best data structure. A more appropriate data structure is a table. A table would allow you to define the interaction of each weapon type against each other weapon type, so you can make any kind of connection between any two weapons.

```
               Bow   Daggers   Spear   MagicalOrb  Gun   Glaive
Bow             0       1        1         1       -1      -1
Daggers        -1       0        1         1        1      -1
Spear          -1      -1        0         1       -1       1
MagicalOrb     -1      -1       -1         0        1       1
Gun             1      -1        1        -1        0       1
Glaive          1       1       -1        -1       -1       0

```

You can read this table like the row is Player1 and the column is Player2, -1 means Player2 wins, 1 means Player1 wins, and 0 means it's a draw.
> 2 votes

---
Tags: rock-paper-scissors
---


# Question
Title: New clients don't see objects spawned before they connect
I'm making a game with `UNet` where the server must create some objects when he connects to the game, and all clients play with these objects that the server has created.

1. A server connects to the game
2. In his start method he calls a function `CmdbuildEverything` to spawn some objects to the game.
3. A local player connects to the game. The local player should be able to see the objects that the server player has created.

The code:

```
public class GameScript : NetworkBehaviour {
    void Start() {
        if(base.isServer)
            CmdbuildEverything();
    }
    [Command]
    void CmdbuildEverything() {
        GameObject ob1 = (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 0, 1), Quaternion.identity);
        GameObject ob2 = (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 1, 0), Quaternion.identity);
        GameObject ob3 = (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(1, 0, 0), Quaternion.identity);
        NetworkServer.Spawn(ob1);
        NetworkServer.Spawn(ob2);
        NetworkServer.Spawn(ob3);
    }
}

```

The problem is that the objects are created only on the server player and don't appear on the clients payers.

How can I solve that?

# Answer
I solved the problem. I found that I should register the prefabs in the network manager registered spawnable prefabs in order to be spawned on all connected devices.
> 1 votes

---
Tags: unity
---


title: C# OpenTK Text rendering

text:
# Question
Title: C# OpenTK Text rendering
I've been looking everywhere for a solution on how to render/draw text for my 2D OpenTK-based game.

Been trying quite a few QuickFont ones without success (either a AccessViolation exception or text just not rendering), which is why I finally decided to ask here.

So my question is; How do I render/draw text in OpenTK for my 2D game?

Thanks!

**EDIT**

I have tried the following example from QuickFont.Desktop GitHub

```
QFont _myFont;
QFont _myFont2;
QFontDrawing _drawing;

_myFont  = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true));
_myFont2 = new QFont("basics.qfont", new QFontBuilderConfiguration(true));
_drawing = new QFontDrawing();  //This line throws exception "Exception thrown: 'System.AccessViolationException' in QuickFont.dll"

```

As I get an error here, It's hard to tell if the rest is wrong or not. It's all in the link above for anyone interested.

What I am looking for is basically a complete "working" guide for the latest OpenTK build with .NET Framework 4.5.2

# Answer
> 7 votes
There's nothing particularly special in how font rendering is handled in OpenTK.

OpenTK - among other things - contains an OpenGL wrapper. And as such any techniques you'd use to render text in OpenGL apply here, namely:

1. Using bitmap fonts - loading font atlas texture and rendering textured quads. BMFont
2. Using geometric primitives (triangles/quads) to render glyphs - vector graphics style.
3. Signed distance fields (SDFs) Improved Alpha-Tested Magniﬁcation for Vector Textures and Special Effects

Here's a complete self-contained sample that:

* generates mono-spaced bitmap font and saves it to disk
* runs an OpenTK example that displays it.
* N.B. will open the generated bitmap font using `Process.Start`;
* Has settings to either use fonts installed in the system or load a font from file (`FromFile` variable);
* If `BitmapFont` variable is true, the atlas texture will be rendered without anti aliasing, for pixelated fonts.

Add reference to `OpenTK` and `System.Drawing` to compile.

```
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;

namespace SimpleText {

public static class Settings {
    public static string FontBitmapFilename = "test.png";
    public static int GlyphsPerLine = 16;
    public static int GlyphLineCount = 16;
    public static int GlyphWidth = 11;
    public static int GlyphHeight = 22;

    public static int CharXSpacing = 11;

    public static string Text = "GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);";

    // Used to offset rendering glyphs to bitmap
    public static int AtlasOffsetX = -3, AtlassOffsetY = -1;
    public static int FontSize = 14;
    public static bool BitmapFont = false;
    public static string FromFile; //= "joystix monospace.ttf";
    public static string FontName = "Consolas";

}

class Program {
    static void Main(string[] args) {
        GenerateFontImage();
        using (App app = new App()) {
            app.Run();
        }
    }

    static void GenerateFontImage()
    {
        int bitmapWidth = Settings.GlyphsPerLine * Settings.GlyphWidth;
        int bitmapHeight = Settings.GlyphLineCount * Settings.GlyphHeight;

        using (Bitmap bitmap = new Bitmap(bitmapWidth, bitmapHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
        {
            Font font;
            if (!String.IsNullOrWhiteSpace(Settings.FromFile))
            {
                var collection = new PrivateFontCollection();
                collection.AddFontFile(Settings.FromFile);
                var fontFamily = new FontFamily(Path.GetFileNameWithoutExtension(Settings.FromFile), collection);
                font = new Font(fontFamily, Settings.FontSize);
            }
            else {
                font = new Font(new FontFamily(Settings.FontName), Settings.FontSize);
            }

            using (var g = Graphics.FromImage(bitmap))
            {
                if (Settings.BitmapFont)
                {
                    g.SmoothingMode = SmoothingMode.None;
                    g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
                }
                else {
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                    //g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                }

                for (int p = 0; p < Settings.GlyphLineCount; p++)
                {
                    for (int n = 0; n < Settings.GlyphsPerLine; n++)
                    {
                        char c = (char)(n + p * Settings.GlyphsPerLine);
                        g.DrawString(c.ToString(), font, Brushes.White,
                            n * Settings.GlyphWidth + Settings.AtlasOffsetX, p * Settings.GlyphHeight + Settings.AtlassOffsetY);
                    }
                }
            }
            bitmap.Save(Settings.FontBitmapFilename);
        }
        Process.Start(Settings.FontBitmapFilename);
    }
}

class App : GameWindow {
    public App() : base(800, 600){}

    int FontTextureID;
    int TextureWidth;
    int TextureHeight;

    protected override void OnLoad(EventArgs e) {
        FontTextureID = LoadTexture(Settings.FontBitmapFilename);
        GL.Enable(EnableCap.Texture2D);
        GL.ClearColor(Color.ForestGreen);
        GL.MatrixMode(MatrixMode.Projection);
        GL.Ortho(0, Width, Height, 0, 0, 1);
        GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
    }

    int LoadTexture(string filename) {
        using (var bitmap = new Bitmap(filename)) {
            var texId = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, FontTextureID);
            BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmap.Width, bitmap.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
            bitmap.UnlockBits(data);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
            TextureWidth = bitmap.Width; TextureHeight = bitmap.Height;
            return texId;
        }
    }

    public void DrawText(int x, int y, string text) {
        GL.Begin(BeginMode.Quads);

        float u_step = (float)Settings.GlyphWidth / (float)TextureWidth;
        float v_step = (float)Settings.GlyphHeight / (float)TextureHeight;

        for (int n = 0; n < text.Length; n++) {
            char idx = text[n];
            float u = (float)(idx % Settings.GlyphsPerLine) * u_step;
            float v = (float)(idx / Settings.GlyphsPerLine) * v_step;

            GL.TexCoord2(u, v);
            GL.Vertex2(x, y);
            GL.TexCoord2(u + u_step, v);
            GL.Vertex2(x + Settings.GlyphWidth, y);
            GL.TexCoord2(u + u_step, v + v_step);
            GL.Vertex2(x + Settings.GlyphWidth, y + Settings.GlyphHeight);
            GL.TexCoord2(u, v + v_step);
            GL.Vertex2(x, y + Settings.GlyphHeight);

            x += Settings.CharXSpacing;
        }

        GL.End();
    }

    public void Blt(double x, double y, double width, double height) {
        GL.Begin(BeginMode.Quads);
            GL.TexCoord2(0, 0);
            GL.Vertex2(x, y);
            GL.TexCoord2(1, 0);
            GL.Vertex2(x + width, y);
            GL.TexCoord2(1, 1);
            GL.Vertex2(x + width, y + height);
            GL.TexCoord2(0, 1);
            GL.Vertex2(x, y + height);
        GL.End();
    }

    protected override void OnRenderFrame(FrameEventArgs e) {
        GL.Clear(ClearBufferMask.ColorBufferBit);
        GL.Disable(EnableCap.Blend);
        Blt(10, 40, TextureWidth, TextureHeight);
        GL.Enable(EnableCap.Blend);
        DrawText(10, 10, Settings.Text);
        SwapBuffers();
    }

    protected override void OnKeyDown(KeyboardKeyEventArgs e) {
        if (e.Key == Key.Escape) Close();
    }
}
}

```

---
Tags: c#, 2d, text, opentk
---


# Question
Title: OpenglGL Render two scenes with one draw call
I need to draw a normal-vector scene and default scene.

I could achieve this my having two programs with different fragment shader to produce the following images. It will require me to draw twice.

```
//somethinglike
useProgram(normal_vector_rendering_program);
render_bunny();
useProgram(just_default_scene_program);
render_bunny();

```

However when I am rendering the default scene, I am already passing normal vector information to achieve the lighting.

So it got me curious, can I produce two different scenes with one program(a program that has two color\_buffer attaches) and one draw call somehow? I think if such is possible then I am saving lots of computer resource by not having to draw multiple times for different images.

# Answer
> 2 votes
http://chat.stackexchange.com/transcript/message/30419781#30419781

> Bind more than one render target. Output two different colors from the fragment shader. You will of course need a second draw call to draw a fullscreen quad containing the render target you want to show. You can also branch every fragment on a uniform if you really want. Fairly straightforward. Unlikely to be saving you a whole lot of "computing resources" for your bunny model though.

---
Tags: opengl, rendering, fragment-shader, frame-buffer, fbo
---


# Question
Title: Playing an animation all the way through with one quick keypress with Mechanim Unity
I have an if statement inside of the Update function that is only called if three other conditions are met. The problem is that right now the function sets a boolean to true which causes the animation to play inside of unity Mechanim. This boolean is only true when I hold down the button, but I would like it to play the whole animation or keep this boolean true for a certain amount of time, thanks and here is my Code.

```
    //Running and jumping animation
    if (Input.GetKey (KeyCode.W) && (Input.GetKey (KeyCode.Space)) && otherAnimation == false) {
        anim.SetBool ("isRunningAndJumping", true);
    }
    else {
        //anim.SetBool ("isRunningAndJumping", false);
    }

```

# Answer
> 0 votes
I figured out how to solve this problem with the help of Kelv.Gonzales. I let the animation play for a set amount of time as I knew that it would last 0.9 seconds. This is the whole piece of code for this problem.

```
//Running and jumping animation
    if (Input.GetKey (KeyCode.W) && (Input.GetKeyDown (KeyCode.Space)) && otherAnimation == false) {
        anim.SetBool ("isRunningAndJumping", true);
        StartCoroutine(WaitAndCallback(0.9f));
        //anim.SetBool ("isRunningAndJumping", false);
    }
    else {
        //anim.SetBool ("isRunningAndJumping", false);
    }

IEnumerator WaitAndCallback(float waitTime){
    yield return new WaitForSeconds(waitTime);
    anim.SetBool ("isRunningAndJumping", false);
}

```

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


title: How to make Pong ai paddle?

text:
# Question
Title: How to make Pong ai paddle?
I'm trying to make an ai so the paddles will move to position before the ball reaches it. I'm not sure how to go about it in this case. Here's the game http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds

```
// Function to increase speed after every 5 points
function increaseSpd() {
    if(points % 4 == 0) {
        if(Math.abs(ball.vx) < 15) {
            ball.vx += (ball.vx < 0) ? -1 : 1;
            ball.vy += (ball.vy < 0) ? -2 : 2;
        }
    }
}

// Track the position of mouse cursor
function trackPosition(e) {
    mouse.x = e.pageX;
    mouse.y = e.pageY;
}

// Function to update positions, score and everything.
// Basically, the main game logic is defined here
function update() {

    // Update scores
    updateScore();

    // Move the paddles on mouse move
    if(mouse.x && mouse.y) {
        for(var i = 1; i < paddles.length; i++) {
            p = paddles[i];
            p.x = mouse.x - p.w/2;
        }
    }

    // Move the ball
    ball.x += ball.vx;
    ball.y += ball.vy;

    // Collision with paddles
    p1 = paddles[1];
    p2 = paddles[2];

    // If the ball strikes with paddles,
    // invert the y-velocity vector of ball,
    // increment the points, play the collision sound,
    // save collision's position so that sparks can be
    // emitted from that position, set the flag variable,
    // and change the multiplier
    if(collides(ball, p1)) {
        collideAction(ball, p1);
    }

    else if(collides(ball, p2)) {
        collideAction(ball, p2);
    }

    else {
        // Collide with walls, If the ball hits the top/bottom,
        // walls, run gameOver() function
        if(ball.y + ball.r > H) {
            ball.y = H - ball.r;
            gameOver();
        }

        else if(ball.y < 0) {
            ball.y = ball.r;
            gameOver();
        }

        // If ball strikes the vertical walls, invert the
        // x-velocity vector of ball
        if(ball.x + ball.r > W) {
            ball.vx = -ball.vx;
            ball.x = W - ball.r;
        }

        else if(ball.x -ball.r < 0) {
            ball.vx = -ball.vx;
            ball.x = ball.r;
        }
    }

    // If flag is set, push the particles
    if(flag == 1) {
        for(var k = 0; k < particlesCount; k++) {
            particles.push(new createParticles(particlePos.x, particlePos.y, multiplier));
        }
    }

    // Emit particles/sparks
    emitParticles();

    // reset flag
    flag = 0;
}

//Function to check collision between ball and one of
//the paddles
function collides(b, p) {
    if(b.x + ball.r >= p.x && b.x - ball.r <=p.x + p.w) {
        if(b.y >= (p.y - p.h) && p.y > 0){
            paddleHit = 1;
            return true;
        }

        else if(b.y <= p.h && p.y == 0) {
            paddleHit = 2;
            return true;
        }

        else return false;
    }
}

//Do this when collides == true
function collideAction(ball, p) {
    ball.vy = -ball.vy;

    if(paddleHit == 1) {
        ball.y = p.y - p.h;
        particlePos.y = ball.y + ball.r;
        multiplier = -1;
    }

    else if(paddleHit == 2) {
        ball.y = p.h + ball.r;
        particlePos.y = ball.y - ball.r;
        multiplier = 1;
    }

    points++;
    increaseSpd();

    if(collision) {
        if(points > 0)
            collision.pause();

        collision.currentTime = 0;
        collision.play();
    }

    particlePos.x = ball.x;
    flag = 1;
}

// Function for emitting particles
function emitParticles() {
    for(var j = 0; j < particles.length; j++) {
        par = particles[j];

        ctx.beginPath();
        ctx.fillStyle = "white";
        if (par.radius > 0) {
            ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false);
        }
        ctx.fill();

        par.x += par.vx;
        par.y += par.vy;

        // Reduce radius so that the particles die after a few seconds
        par.radius = Math.max(par.radius - 0.05, 0.0);

    }
}

```

# Answer
> 1 votes
Simple solution: Have the paddle always move towards the current horizontal position of the ball. When the x-coordinate of the ball is larger than the x-coordinate of the center of the paddle, move it right, otherwise move it left.

Better solution: Extrapolate where the ball will reach the finish-line and have the paddle move towards that point.

In both solutions you can regulate the game difficulty with the speed of the paddle.

# Answer
> 1 votes
You can make an invisible copy of your ball which you update for as long as it didn't reach the paddle.

Here's an example:

Suppose you have a ball class which looks something like this:

```
function Ball(x, y, size) {
    this.x = x;
    this.y = y;
    this.size = size;
    this.vx = 0;
    this.vy = 0;
}

Ball.prototype.update = function () {
   // Move the ball.
};

```

This first thing you want to do in your AI is to make a clone of this ball.

So:

```
var clone = new Ball(ball.x, ball.y, ball.size);
clone.vx = ball.vx;
clone.vy = ball.vy;

```

Then you calculate the distance from the paddle and the ball and update the ball for as long as it didn't reach the paddle.

```
var dx = 0;

do {
    dx = Math.abs(clone.x - paddle.x)

    clone.update();
} while (dx > 10);

```

Now you can simply grab the Y position of your clone.

Ofcourse the paddle now knows exactly where the ball will go when it reaches the paddle. There are two solutions to fix this:

1. Make the loop shorter
2. Add a random value to the final Y position.

Hope this helps

---
Tags: javascript, ai, projectile-physics
---


# Question
Title: Modify the Y position of a GameObject on startup
I'm trying to modify the Y position of a GameObject on startup with the script below:

```
int y;

void Awake()
{
        y = Random.Range (140, 155);

        Vector3 temp1 = transform.position;

        temp1.y = y;
}

```

This script does not modify the Y position of the GameObject on startup. What can I do to fix this?

# Answer
> 2 votes
In Unity, the Vector3 type is a structure, not a class. In C#, structures are value variables, not reference variables. That means the `=` operator creates a copy.

In the line `Vector3 temp1 = transform.position;` you are creating *a copy* of the position. Any changes at that copy are not reflected in the original position. When you want to modify the position, you need to copy it back:

```
    Vector3 temp1 = transform.position;
    temp1.y = y;
    transform.position = temp1;

```

# Answer
> 1 votes
Your code, as it is, isn't actually moving anything. You're assigning a Vector3 and modifying it's Y value, but you're not altering the Y value of the GameObject's transform. Having said that, you can't simply say:

```
transform.position.y = y;

```

Because Unity won't let you. Best way to do this for a beginner would be:

```
void Awake()
{
    int y = Random.Range(140, 155);
    transform.position = new Vector3(0, y, 0);
}

```

That code will move the object to which this script is attached to a random Y position between 140 and 155, with X and Z both at 0. If you want the object to stay where it is in the world, but only move on the Y-axis, use:

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

```

Instead. This will move the object to which this script is attached to a random Y value without altering it's X and Z values.

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


# Question
Title: How do I move a unit one grid-square-width per button press in Unity3D?
I'm learning Unity. I'm making a 2D top down *Frogger*-esque game. I was wondering how you would go about making the player move x pixels per button press.

I have this code to move him, currently with a float for x and y inputs, so he moves slowly:

```
    Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    if (movement_vector != Vector2.zero)
    {
        anim.SetBool("isWalking", true);
        anim.SetFloat("input_x", movement_vector.x);
        anim.SetFloat("input_y", movement_vector.y);
    }
    else
    {
        anim.SetBool("isWalking", false);
    }

    rbody.MovePosition(rbody.position + movement_vector * Time.deltaTime);

```

# Answer
I think the best way to approach this would be to create a grid system where each square is 64x64 pixels, and then have your button press increment the square number. So the frog technically moves 64 pixels, but in code all you'd be doing is saying `gridSquaresX + 1` or something.
> 3 votes

---
Tags: c#, unity, movement, grid
---


title: How could I make someone walk in place?

text:
# Question
Title: How could I make someone walk in place?
I'm working on a serious project and I really need help.

I'm working on a virtual reality First-Person-Shooter game. The problem is that I want to make the player (a real person) walk in place (about only 3 square meters) while playing, and give him the feel of walking, strafing and running, and at the same time detect the distance he should have moved in both axis if he wasn't playing (in real life).

I thought of making him wear shoes containing spheres at the bottom, or making them walk on sliding spheres, but all those are dumb ideas! Any good ideas?

# Answer
> 2 votes
Your ideas don't just sound dumb, they also sound quite dangerous. Remember that a player with a VR headset can not see anything of their *real* surrounding, which greatly increases risk of injury. So safety always needs to be a concern.

What you need (or rather your players need) is an omni-directional threadmill.

The floor of this contraption can move in any direction.

The device detects when the user walks into one direction, and then the threadmill moves them into the opposite direction to bring them back into the center.

The ring on waist height makes sure the player can not fall off the device.

The product from that video (with which I have no affiliation) is not on the market yet, but with a price tag of $700 (just the threadmill without the headset and computer) it seems quite affordable... if it will get on the market and is not just vaporware.

---
Tags: hardware, virtual-reality
---


# Question
Title: Why does my variable seem to be non-existent in GameMaker?
I find myself stuck again with a peculiar issue that I don't really understand.

I'm currently trying to implement a "weapon" into a shooter game (using it as a learning project).

Here is the code pointed by the error message. I'll explain what I'm trying to do right after.

```
  if instance_exists(Player)
  {
    nbtarget=instance_number(ENEMY);
    var i;
    for (i=0;i<nbtarget;i++)
    {
      Target= instance_find(ENEMMY,i)

      if Target != noone
      {
        if Target.size <3 {hit=Target}
      }
      if hit != noone
      {
       if point_distance(x,y,hit.x,hit.y)<startradius
        {
          repeat(2)
          {draw_lightning(x, y, hit.x, hit.y,and other parameters)}

          if damageTik = true
          {
            DMG = instance_create(hit.x,hit.y,Obj_dmg)
            DMG.dmg = Current_dmg
          }
        }
      }
    }
  }
  damageTik= false;
}
else
{
  instance_destroy()
}

```

So, the behavior I was looking for is a lightning that targets every enemy within a radius around the player, only if the enemy size is smaller than 3. Also, the targeted enemy takes a certain damage per second. Everything is working fine.

But, since I implemented that, when I test it, it works fine for a certain amount of time, and then I get this error:

> ```
> FATAL ERROR in
> action number 2
> of Draw Event
> for object lightning_weapon:
> Unable to find any instance for object index '103752' name '<undefined>' at gml_Object_lightning_weapon_DrawEvent_2 (line 15) -if point_distance(x,y,hit.x,hit.y)<startradius
>
> ```

From what I understand, it looks like the instance referred to in the variable `hit` has been destroyed before running the code at line 15. But I'm checking if such instance exists just before `(hit != noone)`, so how can this be? Any pointer will be appreciated.

I try to move the "`instance_destroy()`" part of the enemy code out from the *Step Event* (of the enemy parent object), I tried to move it in the *End Step Event*, then in the *Begin Step Event*, I even tried to make a variable to tell the enemy he is dead and destroy it in the next step... Nothing fixed my issue.

Maybe the problem is not with that part of the code, but after half a day looking at this I can't find any new thing to try.

I also try to do the same with a `ds_list`, but failed to make it work (only one enemy is hit by the lightning):

```
var target = ds_list_create();
with(ENEMY)
{
  if (point_distance(PLAYER.x,PLAYER.y,ENEMY.x,ENEMY.y) < other.radius)
  ds_list_add(target,ENEMY.id);
}

nbtarget = ds_list_size(target)
var i;
for (i=0;i<nbtarget;i++)
{
  hit = ds_list_find_value(target,i)
  if hit != noone
  {
    {draw_lightning(x, y, hit.x, hit.y,other parameters...)}
    if fire = true
    {
      DMG = instance_create(hit.x,hit.y,ODamage)
      DMG.dmg = dmg
    }
  }
}
fire = false;

```

If I manage to make one or the other to work, it's perfect.

# Answer
In the very first code of yours, you wrote:

> `Target= instance_find(ENEMMY,i)`

But that's not correct, since your enemy objects are named `ENEMY`, not `ENEMMY`. Game Maker recognizes "`ENEMMY`" as a different Object Index, and tries to look for an object with that name. But it does not exist, and that's the reason your FATAL ERROR reads:

> `Unable to find any instance for object index '103752' name '<undefined>'`

It is named `'<undefined>'` because it actually doesn't exists. Just fix this typo in your code, and everything will work fine. Or, at least, this error isn't going to show up anymore.
> 3 votes

---
Tags: game-maker
---


# Question
Title: How can I exclude a range of values when generating random numbers?
If you are using `Random.range` to generate values, is there any way to exclude some values within the range (for example: pick a number between 1 and 20, but not 6 through 8)?

# Answer
Instead of throwing away numbers you don't want, you can pretend you want a number from one slightly smaller range, and then map it into the 2 ranges you want:

```
float val = Random.Range( 1, 20 - 8 + 6 );
if ( val >= 6 ) val += 2;

```
> 5 votes

# Answer
You could generate a list of values you want to use, and then pick one at random.

Create values:

```
int[] values = new int[17] { 0,1,2,3,4,5,6,7,10,11,12,13,14,15,16,17,18,19,20 };

```

Get a random value:

```
   int value = values[Random.Range(0, values.Length)];

```
> 3 votes

# Answer
I guess you should go with a solution like this:

```
    int[] validChoices = new int[n]= {1,3,5, whatever until n occurrences};

    private int GetRandom(){
         return validChoices[Random.Range(0, validChoices.Length)];
    }

```
> 1 votes

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


title: Gradient fill color on circular sprite

text:
# Question
Title: Gradient fill color on circular sprite
I have a white circle sprite. I know how to change its color to a solid fill color. using `GetComponent<Renderer>().material.color`. But how would I give it a gradient fill color.

I've been trying to do this with a shader. But so far the shader I've created doesn't take the circle sprite into account, simply its bounding box. It also looks a bit weird.

here's my shader code

```
   Shader "Custom/SpriteGradient" {
 Properties {
 [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
 _Color ("Left Color", Color) = (1,1,1,1)
 _Color2 ("Right Color", Color) = (1,1,1,1)
 _Scale ("Scale", Float) = 1
 }

 SubShader {
 Tags {"Queue"="Background"  "IgnoreProjector"="True"}
 LOD 100

 ZWrite On

 Pass {
     CGPROGRAM
     #pragma vertex vert
     #pragma fragment frag
     #include "UnityCG.cginc"

     fixed4 _Color;
     fixed4 _Color2;
     fixed  _Scale;

     struct v2f {
         float4 pos : SV_POSITION;
         fixed4 col : COLOR;
     };

     v2f vert (appdata_full v)
     {
         v2f o;
         o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
         o.col = lerp(_Color,_Color2, v.texcoord.x );
         return o;
     }

     float4 frag (v2f i) : COLOR {
         float4 c = i.col;
         c.a = 1;
         return c;
     }
         ENDCG
     }
 }
 }

```

# Answer
Pretty old question, but I recently bumped into similar problem and solved it with few more lines of code to my shader. I don't know details of how transparency is handled by Unity when it uses sprite as a texture, but I decided to do same thing Unity does in their default shaders.

You can download 'Built In shaders' from this page: https://unity3d.com/get-unity/download/archive. In DefaultResources folder you'll find Sprites-Default.shader.

Below I paste default shader code where I added my comments to indicate bits that I added to my shader to solve my problem. In general it looks like Unity is using separate alpha mask texture for such sprites, and you need to account for it in your shader.

```
Shader "Sprites/Default"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    }
SubShader
{
    Tags
    {
        "Queue"="Transparent"
        "IgnoreProjector"="True"
        "RenderType"="Transparent"
        "PreviewType"="Plane"
        "CanUseSpriteAtlas"="True"
    }

    Cull Off
    Lighting Off
    ZWrite Off
    Blend One OneMinusSrcAlpha    // I added this line

    Pass
    {
    CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #pragma multi_compile _ PIXELSNAP_ON
        #pragma shader_feature ETC1_EXTERNAL_ALPHA   // and this line
        #include "UnityCG.cginc"

        struct appdata_t
        {
            float4 vertex   : POSITION;
            float4 color    : COLOR;
            float2 texcoord : TEXCOORD0;
        };

        struct v2f
        {
            float4 vertex   : SV_POSITION;
            fixed4 color    : COLOR;
            float2 texcoord  : TEXCOORD0;
        };

        fixed4 _Color;

        v2f vert(appdata_t IN)
        {
            v2f OUT;
            OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
            OUT.texcoord = IN.texcoord;
            OUT.color = IN.color * _Color;
            #ifdef PIXELSNAP_ON
            OUT.vertex = UnityPixelSnap (OUT.vertex);
            #endif

            return OUT;
        }

        sampler2D _MainTex;
        sampler2D _AlphaTex;  // And this line

// I added this whole function
            fixed4 SampleSpriteTexture (float2 uv)
            {
                fixed4 color = tex2D (_MainTex, uv);
#if ETC1_EXTERNAL_ALPHA
            // get the color from an external texture (usecase: Alpha support for ETC1 on android)
            color.a = tex2D (_AlphaTex, uv).r;
#endif //ETC1_EXTERNAL_ALPHA
            return color;
        }

        fixed4 frag(v2f IN) : SV_Target
        {
            // And used it here to get the color of pixel
            fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;
            // and apply alpha
            c.rgb *= c.a;
            return c;
        }
    ENDCG
    }
}
}

```

Hope it helps.
> 2 votes

---
Tags: unity, sprites
---


# Question
Title: my android game works very well on unity editor but not on device
Im working on a android unity project. My game works very well on the editor but, when i build it and run it on blue stacks emulator, it starts working corruptly. Bullets shoot twice in a time. When level is not started, the screen to the next level shows and... what can be the cause of this problem? maybe reason is bad emulator

# Answer
> 1 votes
BlueStacks is just a simulator. Use a real device for testing. Problem is not the build or Unity.

I tried running APK on BlueStacks. It had UI, Shadow etc issues but runs fine on devices.

---
Tags: unity, unityscript, debugging
---


# Question
Title: How can I efficiently render to multiple screens?
I know XNA is long dead, but I need it to update an old project. (I would have ported to MonoGame, but can't get multi-monitor support in it.)

My game does the following:

1. Wait for some objects which I get from server (in another thread)
2. I have some components which represent queue (about 5)
3. When the objects arrive, I generate texture based on the unique information, get a sprite from pool, apply the textures and add it on queue.
4. The game animates the queues from left to right (when one object is added to queue)

So you see lots of unique textures moving on the screen (the update is pretty fast).

Now I need to run two instance of the game to multiple monitors, and there is lag. The frame rate keeps dropping low and clearly the animation is not smooth.

* Is running two games on two threads for two monitors a good idea? What could I do instead (running them on seperate processes)?
* Could some one suggest a rendering optimization like skipping frames or something like that or how can i synchronize between the two instance ?
* Or, even better, how can I draw on two screens from same game instance?

# Answer
> 1 votes
I can't give you exact implementation details for XNA, but the general idea is to completely **forget the "fullscreen mode"** \- it is old and outdated, and at least Windows will not perform any faster with it, as Winodws changed to a DirectX desktop with Vista (or was it Win7?).

Instead, you create an "extended desktop", ie. right-click at desktop / select resolution / see & arrange the blue monitor(s). Set the center monitor as "primary" if you have 3 screens. And perhaps the left one if 2 screens.

Then you output the graphics in **windowed mode**, to the hwnd/hdc of a single borderless and captionless form with dimension(s) exactly as total resolution of all screens together.

Ie. if you want a wide screen render with a large camera FOV, covering all 3 screens completely, just create a 6000 px wide window and place it at correct location, like (-2000,0). It will extend over all monitors. I'm sure XNA provides tools to address specific render areas (viewports) inside the single window, such that an area exactly matches a particular monitor.

System.Windows.Forms provides the Screen class that gives you all needed data to find resolutions, offsets, bounds, whatnot.

You can equally well have two separate processes, each one addressing a window in a separate monitor, the other one just uses screen coordinates like (0,0,2000,1000) and the other one (2000,0,4000,1000). Ofc you may have to slow down the main loop in order to give CPU/GPU time to the othe process, but modern GPU drivers will handle multiple apps gracefully, at least on DirectX.

---

Edit: Also to note: Each time a DirectX window is resized, your video memory will be totally reset. It's a hard device reset. So get ready to re-paint any render surfaces etc. when it happens.

# Answer
> 0 votes
To draw to multiple screens via the graphics devices, you'll need to create your own additional `GraphicsDevice` to draw to. See the constructor:

```
public GraphicsDevice (
     GraphicsAdapter adapter,
     GraphicsProfile graphicsProfile,
     PresentationParameters presentationParameters
)

```

https://msdn.microsoft.com/en-us/library/ff433790.aspx

You can find what graphics adapters there are in your system like this:

```
 foreach (GraphicsAdapter e inGraphicsAdapter.Adapters)
 {
   Console.WriteLine(e.DeviceName);
 }

```

For more info about the adapter information read the MSDN article: https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.graphicsadapter.adapters.aspx

De sure to set the resolution to be within the `SupportedDisplayModes` or the graphicsdevice.

If your videocard has multiple outputs with monitors connected they should come up as separate adapters. You can use the `GraphicsAdapter.IsDefaultAdapter` to find the one that XNA defaults to (and is marked by the Windows as the 'default' desktop adapter).

I've not yet tested to output to two screens simultaneously; I did a small test project once to redirect output to a adapter of my choice.

---
Tags: xna, performance, multiple-graphics-devices
---


# Question
Title: What is the name for the kind of game of jumping dinosaur from Chrome's 404 page?
Basically, I want to know the name so I can find if anyone already built a clone game with PhaserJS like the one of jumping dinosaur from Chrome's 404 page.

# Answer
> 3 votes
It's a 2D *infinite runner*. It's a particular type of 2D side-scrolling games, the levels are generated dinamically, objects and obstacles are as well. It's the same mechanics of Jetpack Joyride and similars.

---
Tags: terminology
---


# Question
Title: How can I convert an orthographic camera to a perspective camera?
How can calculate perspective camera parameters from orthographic camera parameters (left, right, top, bottom, near, far)?

Specifically I don't know how calculate the FOV for a perspective camera from orthographic camera.

# Answer
> 5 votes
You can't.

The two matrices are constructed in completely different ways.

There are tons of ways to find more information on that by googling.

You can't get the field of view from the orthographic camera because there is no such thing.

---
Tags: camera, perspective
---


# Question
Title: How to use NoSQL REST API of Gamesparks in my Unity project?
Gamesparks has a documentation of the API but I am not sure how to send https requests to use that API.

# Answer
> 0 votes
I'm part of the customer success team at gamesparks.com Rest is generally reserved for server to server communication and it would be considered bad practice to use it in your unity client as it adds additional and unnecessary steps.

My advice would be an event that constructs the NoSQL query from data passed as attributes into the event. The query can be constructed from this data. Best Regards, Patrick.

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


# Question
Title: How to apply Buoyant force to a Box2d body?
I have been following a formula to calculate the buoyant force needed to apply to a dynamic body to be able to simulate water.

> Fb = ρgV

1. Fb - is the buoyant force
2. ρ - density of the liquid
3. g - gravity
4. V - volume of the object

My box2d body will always be submerged to the sensor so I don't have to detect what portion of the body is in the water, basically the entire body is always in the water and I will always apply the force to the center of the body.

```
body.applyForceTocenter(0, Fb, true);

```

If I apply the force on upon collision to the censor then it will just fall cause there is not enough force, and if I type this to the render method then the body will fly cause there is too much force. So how do I implement the force? and how to compute for the drag? so that it won't bounce.

# Answer
Your primary question is:

> So how do I implement the force?

Considering that your body is always underwater, there's an easy way out of this one: just use gravity :) As iforce2d points out in his tutorial on custom gravity, you can set the gravity scale of any object:

```
//Box2D v2.2.1 onwards
body->SetGravityScale(0);//cancel gravity (use -1 to reverse gravity, etc)

```

So if you can control the bouyant force by tweaking the value you pass to `setGravityScale`. As long as it's less than 0 your object will be bouyant.

As usual if you want your body to experience drag then use `setLinearDamping`.

If you want to control the bounce then set the `restitution` field to some value between 0 and 1 when you create the fixture, or use the appropriate method to change it when the fixture has been created.
> 1 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: Fixed timestep with interpolation & rounding draw positions: jerky animation when the character is not moving
I've implemented a deterministic, fixed timestep system from here: http://gafferongames.com/game-physics/fix-your-timestep/

Everything works fine, output is the same with each step but there's one problem - the animation is jerky while the character isn't moving.

Here's the code responsible for interpolation:

```
    draw.x = previous.getX() * alpha + current.getX() * (1.0f - alpha);
    draw.y = previous.getY() * alpha + current.getY() * (1.0f - alpha);

    g2d.drawImage(image, (int)draw.x, (int) draw.y, null);

```

Here's how 'alpha' looks like:

```
0.29991353
0.35988057
0.41996205
0.41996205
0.4799291
0.4799291
0.53989613
0.5998632
0.5998632
0.65994465
0.7199117
0.97999954
0.039999668
0.099999785
0.1599999
0.21999958
0.2799997
0.33999982
0.39999995
0.4599996
0.51999974

```

Let's assume that player's initial position is x = 100 and he's not moving.

His interpolation gives values like 100.0000123123 (which when casted to int gives 100 - OK) but it also gives values like 99.99999998, which when casted to int gives 99 (which makes the jerk).

I don't know how to handle this, maybe just make a statement (if previous != current then do interpolation) and that's it?

Thanks very much

**Edit** Here's my gameloop:

```
    float fps = 60;
    float dt = 1 / fps;
    float accumulator = 0;

    Time time = new Time();
    float frameStart = time.getSeconds(); - // returns seconds since initialization for ex. 1.32234, 6.43243

    while(match_running) {

        float currentTime = time.getSeconds();

        accumulator += currentTime - frameStart;

        frameStart = currentTime;

        if (accumulator > 0.2f)
            accumulator = 0.2f;

        while (accumulator > dt) {
            doPhysics(dt);
            accumulator -= dt;
        }

        float alpha = accumulator / dt;
        gamePanel.drawGame(alpha); // here's the interpolation

    }

```

# Answer
It sounds like you simply need to *round* the interpolated position to the nearest integer, instead of truncating it (as float → integer conversion normally does). A simple trick (for non-negative values) is simply to add 0.5 to the value before truncating it:

```
g2d.drawImage(image, (int)(draw.x + 0.5f), (int)(draw.y + 0.5f), null);

```

(I'm assuming that `draw.x` and `draw.y` are floats. If they're integers, you should add the 0.5 to the previous expressions where you calculate them instead.)

Note that this can still produce apparent jitter if the (floating-point) position ever happens to lie precisely halfway between two integer pixel coordinates. If this is an issue for you (which it might not be, depending on how likely your game physics is to trigger this edge case), you can fix it by implementing hysteresis, something like this:

```
if (abs(draw.x - draw.xInt) > 0.75f) draw.xInt = (int)(draw.x + 0.5f);
if (abs(draw.y - draw.yInt) > 0.75f) draw.yInt = (int)(draw.y + 0.5f);
g2d.drawImage(image, draw.xInt, draw.yInt, null);

```

This will ensure that the rounded position of the object (stored in `draw.xInt` and `draw.yInt`) will not change unless the interpolated position moves more than 0.75 pixels away from the previous rounded position (whereas direct rounding would cause the rounded position to change as soon as the interpolated posititon moves over 0.5 pixels away from it along either axis). If you want, you can fine-tune the tradeoff between stability and precision by replacing the threshold value 0.75 with any value between 0.5 and 1.0, but in practice, 0.75 should be a reasonable default to start with.

(Without seeing the rest of your code, I have no idea if you really need to have both `draw.x`/ `draw.y` and `draw.xInt` / `draw.yInt` as separate members. But it was the minimal change to your existing code to demonstrate the technique.)
> 1 votes

# Answer
Why does my position interpolation code result in "jumpy" motion?

> Make sure previousPosition\_ is only being updated when there's a new physics update, not every frame

But I still don't know if it's a good solution.
> 0 votes

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


# Question
Title: How do I find out at runtime if Vulkan and/or OpenGL support is available?
I'm building an engine, which has Vulkan for its primary rendering engine. But to have at least some backwards compatibility with devices that don't get drivers for (Mainly mobile) it I want to implement an OpenGL fallback. Now, how do I check what API's are available in the current system?

I want to check if Vulkan support exists, if not then if GL support exists and if not that then crash.

# Answer
Your first check is likely to be a `LoadLibrary` call (or equivalent for your platform) for the Vulkan DLL:

```
HMODULE vulkanDll = LoadLibrary("vulkan-1.dll");

```

Then you'll want to acquire the pointer to `vkCreateInstance`.

```
PFN_vkCreateInstance vkCreateInstance;
// ...
vkCreateInstance = GetProcAddress(vulkanDll, "vkCreateInstance");

```

Then you'll want to fill out the appropriate parameters and *call* `vkCreateInstance`. This can be involved, you'll want to read the documentation. `vkCreateInstance` will return a result code which may indicate that it has failed to load. If it fails or if any of the prior steps fail (with an error that is not "you called the function wrong" or similar), Vulkan's not available, fall back to OpenGL.

The above is a fairly low-level, library (but not OS) agnostic approach; if you're using additional frameworks they may abstract away some of this work for you. For example, GLFW apparently provides a function you can use to tell if Vulkan is available.

---

For OpenGL, pretty much everything already has the DLL or equivalent available, but you can apply the same `LoadLibrary` et cetera steps if you want. Initializing OpenGL is a more platform-specific task, which seems out of scope for this question, but it can fail: if it fails, OpenGL is for some reason not available.

Chances are it will succeed, though, but you may have fallen back to a version of OpenGL you did not want or that is too primitive for your game. You can call `glGetString` with `GL_VERSION` to determine the actual version of OpenGL you were able to load. Other values, such as `GL_VENDOR` or `GL_RENDERER`, may tell you information about the driver you are interested in. Based on that you can determine if your overall OpenGL load was "successful" per your own metrics and handle that accordingly (crashing, in your case).
> 6 votes

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


# Question
Title: How can I efficiently render a large, zoomable world map?
We are looking to develop a grand strategy PC game in Unity with a world map similar in scale to Crusader Kings 2 and Europa 4.

We want to add more details to the map so that we can stand out visually, but we are worried that such a large zoom-able map, rendered in 3D, will cause performance issues.

How can we deal with efficiency problems related to rendering such a large map at various levels of zoom?

# Answer
> 3 votes
The search term you are looking for is "Level of Detail" or "LOD". It basically means that you adjust the level of detail of the map depending on the zoom factor.

You can have a really high level of detail on the highest zoom level. When the player zoomed in so far that there aren't many objects on the screen, you can get away with that without losing too much framerate.

When the player zooms out they can't discern that level of detail anyway, so you can remove small objects and replace larger objects with lower-polygon versions. That way the framerate stays acceptable and when you do it well the player won't even notice.

The Clausewitz engine by Paradox (the graphic engine used by CK2 and EU4) in fact does that as well. Compare how a city is rendered on these three screenshots which were made from marginally different zoom levels. As you can see the buildings are first replaced with simpler models and then all but the largest one are removed altogether:

The Unity terrain system already has that built in (including for the speedtree-based trees). For other 3d objects, you can use the LOD group component.

---
Tags: terrain-rendering, level-of-detail
---


title: Object outlining

text:
# Question
Title: Object outlining
I have an object whose boundaries can be define using a convex collider. I have an AI which needs to outline that structure to patrol it. The object is dynamic and composed of pieces like LEGO, each having its own convex collider. I am looking for algorithms that can be used to trace this dynamic object, maintaining a variable distance away from the object.

Below is an illustration of the issue,

* Red - Long Distance Trace
* Green - Short Distance Trace
* Black - Structure

I would need the AI to trace both the red (Long distance trace) and the green (Short distance trace) path. What path algorithm should I use for this?

Here are some examples to consider

# Answer
**Raycasts and steering**

You'll find the path as you go, casting rays and checking for different cases.

* Pink - Your entity
* Red - Offset ray. Cast perpendicular to the forward of your entity. Maintains a specific distance from the wall and used to ensure the wall is still there.
* Blue - Look ahead ray. Looks ahead for the wall and is responsible for the origin of the green ray.
* Green - Normal ray. A ray from the contact point of the Blue ray, in the direction of the normal of the surface. Used to detect if an opening is too small to enter.

Here the lookahead ray and green ray determine that the passage ahead is too narrow to go down. This is because the green ray hit a wall. This triggers a turn opposite the Offset ray, in this case, to the right.

Here, the lookahead ray detected a wall perpendicular to the forward vector (you should create your lookahead ray to detect these situations before the red ray detects the end of the wall). This triggers a right turn.

Once again, we've found a wall perpendicular to the forward vector. Turn right.

Here, the red ray finds that the wall has run out, this means a left turn.

And again, the red ray finds the wall has run out, left turn.

So the cases we're looking for:

1. Lookahead ray finds a passage that's too small to enter, turn away from red ray.
2. Lookahead ray finds a wall in front of us, turn away from the red ray.
3. Red ray finds the wall has ended, turn towards red ray.

The green line is a fairly trivial modification, where we just have a small lookahead that looks directly ahead and turns opposite the red ray when it detects a wall. And the red ray turns towards the red ray when it detects lack of wall.
> 3 votes

# Answer
Use the normals of your surfaces to calculate this.

Essentially, you're taking your existing edge, and growing it. Then, in some cases, optimizing it to cut out loops or tight corners.

For each corner, you get the averaged normal for the two surfaces that make up that corner. For interior corners, since the average would be pointing towards each other, you'd use the cross product to get the perpendicular vector.

This will grow the edge. This works great for your green line, since it's the same edge as your shape. However, for your red line, this can produce problems. You can use some pathfinding shortcut techniques to optimize out sharp turns.

For example, you'd want the shortcut between 4 and 9, so you can skip 5-8. There's a few approaches to this. For example, detecting loops, like 5-8 would create or a pathfinding optimization for reducing redundant nodes.

Check page 12.

Likely the easiest way of detecting these loops is to find nodes that are close together and remove them. Build up your entire path, then test each node and its neighbors to ensure they aren't too close. If nodes are removed, repeat the comparison until no nodes are removed. In my example image, nodes 6 and 7 would be removed for being too close. That would reorder nodes 5 and 8 to be nodes 5 and 6. Then nodes 5 and 6 would be removed for being too close. After that, there are no more nodes that are too close.
> 2 votes

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


title: What does this code mean?

text:
# Question
Title: What does this code mean?
I got some code from here http://www.williammalone.com/articles/create-html5-canvas-javascript-game-character/1/

Everything is quite understandable, everything working well. However, I don't understand what breathDir could stand for.

```
function updateBreath() {

  if (breathDir === 1) {  // breath in
    breathAmt -= breathInc;
    if (breathAmt < -breathMax) {
      breathDir = -1;
    }
  } else {  // breath out
    breathAmt += breathInc;
    if(breathAmt > breathMax) {
      breathDir = 1;
    }
  }
}

```

# Answer
All it does is make the 'breathAmt' variable travel go up and down between 1 and -1 over time.

This gets combined with the next snippet of code, about a few paragraphs down on the page:

```
function redraw() {

  canvas.width = canvas.width; // clears the canvas

  drawEllipse(x + 40, y + 29, 160 - breathAmt, 6); // Shadow

  context.drawImage(images["leftArm"], x + 40, y - 42 - breathAmt);
  context.drawImage(images["legs"], x, y);
  context.drawImage(images["torso"], x, y - 50);
  context.drawImage(images["head"], x - 10, y - 125 - breathAmt);
  context.drawImage(images["hair"], x - 37, y - 138 - breathAmt);
  context.drawImage(images["rightArm"], x - 15, y - 42 - breathAmt);

  drawEllipse(x + 47, y - 68 - breathAmt, 8, 14); // Left Eye
  drawEllipse(x + 58, y - 68 - breathAmt, 8, 14); // Right Eye
}

```

The redraw you can see in the 'y' parameter the 'breathAmt' is being subtracted from another variable. In this case 'y' means height - so the images for the different body parts are being drawn at a very, very slightly different height depending on what the value of 'breathAmt' - which makes the character being drawn kind of look like he's breathing.
> 0 votes

---
Tags: javascript, html5
---


# Question
Title: How to distinguish between full/partially intersecting Collider2D?
I'm using Unity 5 to make 2D game.

I have a screen (gray), arena (green) and player-controlled object (yellow) that can be moved across the screen with mouse before placement:

There is no Rigidbody2D attached to arena or object.

Is it possible to check whether the object is fully inside the arena or partially inside it **using built-in Unity physics API**?

I know that it can be easily calculated in this case, but I want to know, is it ever possible.

# Answer
> 1 votes
As you probably already know based on how you formulate your question, the physics engine only registers collisions whn at least one of the colliders have a rigidbody attached. In many cases you can just add a kinematic rigidbody that is not affected by gravity to get a collision detection going. Unfortunately the Collision2D.ContactPoints, which is of type ContactPoint2D, do not let you know the interpenetration amount so you'll need to decide the entirely inside part yourself.

If adding a kinematic rigidbody is not a possible solution for you there is actually one other approach to using the physics engine. If you check the static methods of the Physics2D class you'll notice that there are several methods named "cast", e.g. CircleCast. These actually **can** be used to check even against static colliders with no rigidbodies. They all return a RaycastHit2D which will not tell you if the entire cast was inside the collider so you'll still have to figure that part out yourself.

A third possible solution would be to use a custom collider to create a collider that covers the areas around your "arena". This could be done using e.g. the edge collider to create a circle around the arena. It will only create a set of edges though, so you'll also need to check that the collider you want to check for is not entirely outside (e.g. by circle cast against a circle collider in this case).

---
Tags: unity, physics, box2d
---


title: How to switch between sprites in Unity

text:
# Question
Title: How to switch between sprites in Unity
So I made an empty game object in inspector, called it "squareTest", and I clicked and dragged 3 sprites in. One is the square being black, one is the square being red, and one is the square being green. What I want to do is this:

In the code, it starts by default as the black sprite. Whenever 'x' happens, the sprite changes to the red square. And whenever 'y' happens, it changes to the green square. BTW, x and y could mean anything. I just want some logic to it, as in

```
if (password == "Open sesame") {
    //Change square color
}

```

My game programming experience is from Pygame, and this problem could have been solved like this (using a sprite sheet that goes from left to right)

```
if Condition:
    square_spritesheet.current_frame = 5

screen.blit(square_spritesheet.texture, (x, y),
(self.current_frame*self.frame_width, 0, self.frame_width, self.frame_height))
#screen.blit goes (image, (x, y),
#(start chopping_X, start chopping_Y, end chopping_X, end chopping_Y)

```

Unfortunately, I do not have a clue how this could be accomplished in Unity. I do not know if this is possible with an animator controller. I just want to know if this is possible, and how it could be achieved, with or without an animator. Thank you very much!

The different colored squares are different textures, and I do not need transitions between states.

# Answer
I'd write a little script like this and attach it to the object displaying the sprite:

```
[RequireComponent(typeof(SpriteRenderer))]
public class SpriteSwitcher : MonoBehaviour {

    // Populate this array in the Unity Inspector window
    // to contain the sprites you want to switch between.
    public Sprite[] sprites;

    SpriteRenderer _spriteRenderer;

    // Use this for initialization
    void Start () {
        // Cache a reference to this component so we don't
        // need to look it up every time we want to use it.
        _spriteRenderer = GetComponent<SpriteRenderer>();
    }

    public void SwitchToSprite(int index)
    {
        // Catch errors where we accidentally passed an index out of range.
        if(index < 0 || index >= sprites.Length)
        {
            Debug.LogError("Attempted to display a sprite outside the valid range: " + index);
            return;
        }

        // Display the selected sprite.
        _spriteRenderer.sprite = sprites[index];
    }
}

```

Because the `SwitchToSprite()` method is public, we can use the Inspector to wire up a UI button to call it when clicked and pass the index of the sprite we want to display:
> 1 votes

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


# Question
Title: XNA HLSL Shader Color Swapping based on lightness
I'm trying to achieve a similar effect to the image below in HLSL.

\[Ignore the inbetween state, currently I'm only trying to achieve the final phase, which is black and red\]

What I tried so far is to sample based on which colors we perceive as brighter, ore more intense and separate the sampled colors to red and black based on that.

Code for what I've tried below:

```
    float4 PixelShaderFunction5(PixelShaderInput input) : COLOR0
{
    float4 src = tex2D(ColorMapSampler, input.TexCoord);
    float4 final = float4(0.6F,0,0,1);
    float4 final2 = float4(0,0,0,1);
    double a = 1 - ( 0.299 * src.r + 0.587 * src.g + 0.114 * src.b)/1;
    if(src.a >0)
    {
    if(a>0.5)
    {
    return lerp(src,final,limit);
    }
    else return lerp(src,final2,limit);
    }
    else return src;
}

```

But this doesn't seem to result in the same effect.

Could anyone suggest me possible ways to have a similar color swapping shader?

Thanks in advance.

# Answer
> 0 votes
To create this effect convert the pixel to greyscale:

```
float grayscale = dot(color.rgb, float3(0.3, 0.59, 0.11));

```

Then return red above the threshold and return black below it (while preserving the alpha). See what threshold value works for you.

---
Tags: xna, 2d, shaders, hlsl
---


title: Libgdx if statement is not working well

text:
# Question
Title: Libgdx if statement is not working well
I am trying to make the player die when it hits the rock or the time is up and the score is not reached, in this code at the first if statement it works when Rockhit is true, the player jump and disappear at the bottom of screen and the music is work very well, but when the time is 0 and score is not reached , the player is jump and keeps going out of the top of screen and the sound is work but slow and not clear. (notice: that before I adding the Rockhit condition the player was going up out of screen and the voice wasn't clear) this is the code:

```
  public State getState()
        {
            //Gdx.app.log(Float.toString(b2body.getLinearVelocity().x),"hi");
            if ((Hud.getTime()==0&& Hud.getScore()<(level*15)+50)|| Rockhit()) {
                Fruits.manager.get("music/Backmusic.ogg", Music.class).stop();
                collectoIsDead=true;
                Filter filter = new Filter();
                filter.maskBits = Fruits.NOTHING_BIT;
                for (Fixture fixture : b2body.getFixtureList())
                    fixture.setFilterData(filter);
                b2body.applyLinearImpulse(new Vector2(0, 5f), b2body.getWorldCenter(), true);
                //b2body.applyLinearImpulse(new Vector2(0,-2.5f), b2body.getWorldCenter(), true);
                Fruits.manager.get("music/fail.mp3", Sound.class).play();
                return State.DEAD;

            }

            if((Hud.getTime()==0&& Hud.getScore()>=(level*18)+50)|| (Hud.getScore()>=(level*15)+50)) {
                Fruits.manager.get("music/Backmusic.ogg", Music.class).stop();
                Fruits.manager.get("music/cheering.mp3", Sound.class).play();
                return State.SUCCESS;
            }
            if (b2body.getLinearVelocity().x!=0)
                return State.RUNNING;
            else
                return State.STANDING;

}

```

# Answer
I don't know if the method you posted is called every frame, but `(Hud.getTime()==0&& Hud.getScore()<(level*15)+50)` will always be true once the time is up. (thus giving that linear impulse and starting the sound every frame). I would try to nullate the score.
> 1 votes

---
Tags: java, libgdx
---


title: Black lines on sprites

text:
# Question
Title: Black lines on sprites
I am having the issue as seen below while using a textureAtlas with libgdx. I haven't found anyone else with the issue so I decided to ask here.

Here is an image of the textures in the game screen:

And to prove it's not a texture related issue, here is the spritesheet with the same background color as the game screen has applied:

Any suggestions? sorry for the sloppy write-up I am very preoccupied.

# Answer
Turns out the answer has to do with alpha channels and the way they were being processed. I removed transparent pixels from the edges and it works as intended now.
> 1 votes

---
Tags: java, android, libgdx, sprites
---


# Question
Title: is it possible to use Ui button to work continous on unity
i want to use Ui buttons as joyStick arrows to move character. but as i know buttons just work once. not continous. so is it possible to make button work continous?

# Answer
You can add an event trigger with Pointer enter.

Add a Event Trigger component with the UI object. Add input as Pointer Enter. Refer the object as you do with Button object and select the public function on the script.
> 1 votes

---
Tags: unity
---


# Question
Title: how to work more efficient with UI elements
im working on a mobile android game that has many levels and same UI. for every level i have to assign the object and function of every button in every scene level.

is there more effiecient way that there will be no need to assign all functions in every scene?

thank you for helping

# Answer
> 3 votes
Use tag for the common UI objects. Get them in the Start() or Awake() with GameObject.FindWithTag("tag").

When you get the object you can access all the components in them in runtime as you assign at editor inspector.

After getting the object, for event triggers you will have to work with their delegates. Handling event trigger delegates in runtime

Keep the tags meaningful. Will be a great help.

Edit: more useful link.

# Answer
> -1 votes
if they have the same UI and the same behaviour you could transform all UI such like HUDs, In-Game Menus into a prefab intantiate or drag to your hierarchy. I did it for exemple in virtual D-Pad made of Button class and Game Over and Level Cleared Screens

---
Tags: unity
---


# Question
Title: Can a partially completed game be sold to a game development company for completion?
I'm a lone programmer with an idea for a game. I believe I can code the mechanics of the game by myself. I do not think I have the expertise, time, or creativity to create the graphics and audio of a marketable game. I have a very good understanding of how to design applications that are loosely coupled to their front ends and I feel I could create the game with an ugly UI.

I was wondering if I were to create a game, would I then be able to sell or license my game to a game development company that has the resources to replace my UI with quality work? If this can work, are there any examples of other people doing it?

I imagine the scale of the game would be a consideration for this approach. A large scale game would probably be more attractive, but there is no way a lone programmer could create it to begin with. A small scale game may not be worth the time for a game development company.

# Answer
# This has already happened

All Points Bulletin was started by Realtime Worlds. RTW failed to bring it to completion as they went into administration in 2010 and ceased to exist. Reloaded Inc took over, re-releasing the game as **APB:Reloaded**, a free-to-play team vs team sandbox shooter.

*Doing the Unflinching Walk in the city of San Paro*

Now, 6 years later they are still developing the game.

Now granted: this has been tough for Reloaded. RTW left the code in a state that is best called "a complete mess". Despite using the Unreal Engine, RTW had used so much custom code that Reloaded has had a very hard time to develop the game because as soon as they touch one thing, three others break. They have struggled for over **two years** now to try to replace the old 3.0 customized Unreal Engine with a standardized 3.5 UE, so they can do some actual work on the game without breaking it every time.

Thankfully that work now seems to be coming to a close, as they have gone into a beta release (or "soft launch") of the XBox One version, based on the new(er) Unreal Engine.

So yeah, it is feasible. But do not expect it to be an easy ride.

As for the core of your question:

> I was wondering if I were to create a game, would I then be able to sell or license my game to a game development company that has the resources to replace my UI with quality work? If this can work, are there any examples of other people doing it?

You are kind of missing the point here. **Coding** is not the issue. **Development** of the game involves so much more than that. What you are selling is not the **code**, you are selling the **concept** of the game... the **intellectual property** that is the game.

Is this possible?

Oh yes... just look at Portal. Not only did Valve buy the concept, they even hired the programmers that made the predecessor freeware game that demonstrated the concept, Narbacular Drop.
> 2 votes

# Answer
Anything is possible, but the situation you describe is **highly improbable**. Software developers rarely like picking up where someone else left off, and are much less likely to *pay* for that opportunity.

However, you might be able to create a technical demo to try to pitch your game. Either to gain the funds (via crowdsource or otherwise) to hire developers yourself, or to gain the attention of a publisher who might hook you up with a development company. Either way, it's likely the game will be rewritten from scratch.
> 10 votes

# Answer
This is *technically* possible. You can take any game you've created and sell it or license it out or engage in a contract with somebody else to extend or to finish it (provided you own the right to do so for all code and assets you used, et cetera, et cetera, et cetera).

In *practice*, however, this is unlikely to work out for you. Generally companies already have plenty of their own ideas and projects to develop, or are paid to develop somebody else's idea or game rather than paying for it themselves.
> 5 votes

---
Tags: game-industry, marketing
---


# Question
Title: How to improve this random number generation in my context?
In my game there is a word at top of the screen, letters are raining down from top and the user has to touch the letters to complete the word.

Currently I am generating letters randomly (actually random numbers and numbers are the index for the array of letters. e.g: 0=a, 1=b) but the problem is that it takes too much time to get all the required letters to complete the word.

What I want is that the random numbers that I am generating should generate required letters more often so player don't have to spend all day to complete one word.

I have tried following methods:

1. Detect all the letters in the word (word is always 6 letters long), generate the array of indexes of length 6, assign each index of the array to random number from letter-2 to letter+2 and in the end pick randomly one index from the array to show.
2. Have a selector variable whose value is in the range \[0..2\], generated randomly, if selector == 0 then detect letters which make the word and randomly pick one letter, else randomly get any alphabet from a-z.

Both of these methods have not provide me with any help. I will be very happy if you can help me.

Thanks for reading this, I hope you understood the question and I am waiting for the response.

# Answer
> 20 votes
You don't actually want a random distribution. I point this out explictly, because what we consider "random" for design is usually not true randomness.

Now, with that in mind, let's add some tweaking values -- these are things you'll fiddle with until the design feels "right".

```
ChooseLetter() {
    const float WordLetterProbability = 0.5f;
    if (Random.NextFloat01() < WordLetterProbability) {
        // Pick a random letter in the word
    }
    else {
        // Pick a random letter *not* in the word
    }
}

```

The probability controls how likely a given call to ChooseLetter will give you a word letter -- at 0.5, you'll get a word letter roughly every other time. At 0.25, one out of four will be a word letter, etc.

This is still a bit simplistic -- because randomness is, well, *random*, you don't actually have a guarantee on how long you'll go between word letters. (In theory, you can go *forever* without a word letter, it's just very very unlikely.) Instead, we can add a factor to increase the probability of a word letter every time we don't get one:

```
const float BaseWordLetterProbability = 0.5f;
const float WordLetterProbabilityIncrease = 0.25f;
float WordLetterProbability = BaseWordLetterProbability;
ChooseLetter() {
    if (Random.NextFloat01() < WordLetterProbability) {
        // Pick a random letter in the word
        WordLetterProbability = BaseWordLetterProbability;
    }
    else {
        // Pick a random letter *not* in the word
        WordLetterProbability += WordLetterProbabilityIncrease;
    }
}

```

Okay, so now we never go more than two letters without a word letter. (Because, after two misses, we have a 1.0 probability of getting a word letter.)

Finally, we need to take in to consideration how choosing the letter in a word works. In order to provide the player with the letters they *actually* need, we need to remove letters from the set as they get them.

For example, if the word is "test", and the player already has 's', we don't want to give them another 's', because they don't need it!

From here, the rest is tweaking to fit your design.

# Answer
> 20 votes
You could weight the probability of all your letters according to the frequency with which they occur in the language your words are in. A good guideline is the scrabble set. The English version, for example, has 12 E's but only one Z and one Q.

A simple way to implement this is by putting all the letters in a consecutive string with each letter appearing as often as desired and then have your RNG take a letter from a random position. Pseudocode example:

```
const String letters = "AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJ/*...and so on...*/"

char randomLetter = letters[randomIntegerBetween(0, letters.length - 1)];

```

# Answer
> 4 votes
Here is one way to improve it using one single parameter `k` that you can tweak.

Instead of just picking a random letter:

1. pick a random letter `A`
2. pick a random number `X`
3. if `X > k` *and* `A` is not in `[list of remaining needed letters]`, try again at 1.

The smaller `k` is, the more often the final letter `A` will be one that is actually needed.

To tweak the algorithm, play with any value for `k`, *e.g* `k = 0.5`. If you find the game is too hard, try `0.4` instead, etc. until you find a reasonable value. This also directly gives you a **difficulty setting**, which for instance you may want to increase as the player advances in the game.

# Answer
> 3 votes
A simple way to guarantee that the required letters show up within a given time is to use fill an array with the letters in the word and the rest of the alphabet (perhaps repeated), then randomly shuffle the array (c++ has std::random\_shuffle in the standard library, if you're using a different language it is not difficult to implement).

If you want the letters in the word to show up more quickly, put more copies of the word-letters in the array.

# Answer
> 0 votes
If you are using C++ you can use an already existing distribution http://en.cppreference.com/w/cpp/numeric/random/piecewise\_constant\_distribution

It also has amortized constant time complexity which is better than naive methods. example:

```
#include <iostream>
#include <string>
#include <map>
#include <random>
#include <numeric>

int main()
{
    constexpr double containedLetterWeight = 3.0;
    constexpr int iterations = 10000;
    std::string word = "DISTRIBUTION";

    std::mt19937 rng(123);

    std::vector<double> values('Z' - 'A' + 2);
    std::iota(values.begin(), values.end(), 0.0);

    std::vector<double> weights('Z' - 'A' + 1, 1.0);
    for(const auto& c : word) weights[c - 'A'] = containedLetterWeight;

    std::piecewise_constant_distribution<> dist(values.begin(), values.end(), weights.begin());

    std::map<char, int> results;
    for(int n = 0; n < iterations; ++n)
    {
        ++results[static_cast<char>(dist(rng)) + 'A'];
    }
    for(const auto& p : results)
    {
        std::cout << p.first << ' ' << static_cast<float>(p.second) / iterations << '\n';
    }
}

```

---
Tags: random
---


title: OpenGL cube map is always black

text:
# Question
Title: OpenGL cube map is always black
When creating and rendering a skybox with a cube map texture, the skybox is black.

Here is how I create the cube map texture:

```
GLuint loadCubemap(std::vector<std::string> faces)
{
    GLuint textureID;
    glGenTextures(1, &textureID);
    glActiveTexture(GL_TEXTURE0);

    int width,height;
    unsigned char* image;

    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
    for(GLuint i = 0; i < faces.size(); i++)
    {
        image = SOIL_load_image(faces[i].c_str(), &width, &height, 0, SOIL_LOAD_RGBA);
        glTexImage2D(
                    GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,
                    GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image
                    );
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

    return textureID;
}

```

Here is how I draw the cube map:

```
void Skybox::update()
{
    //the sky box should be in the background
    glDepthMask(GL_FALSE);

    //set the position of the skybox around the camera
    pos = Camera::getCurrentlyBound()->getPos();

    //faces of the cube map
    std::vector<std::string> faces = {
        "/home/a/Programming/GameEngine/Game/Assets/skybox_px.png", //+x
        "/home/a/Programming/GameEngine/Game/Assets/skybox_nx.png", //-x
        "/home/a/Programming/GameEngine/Game/Assets/skybox_py.png", //+y
        "/home/a/Programming/GameEngine/Game/Assets/skybox_ny.png", //-y
        "/home/a/Programming/GameEngine/Game/Assets/skybox_pz.png", //+z
        "/home/a/Programming/GameEngine/Game/Assets/skybox_nz.png", //-z
    };

    //create the texture object
    GLuint cubeMap = loadCubemap(faces);

    //set up some matrices
    glm::mat4 modelMatrix = glm::translate(glm::mat4(), pos)*glm::mat4_cast(orien);
    glm::mat4 mvpMatrix = Camera::getCurrentlyBound()->getVP()*modelMatrix;

    //you can ignore this part
    Program* prog = ProgramManager::getProgram(msh.getProgramPath());

    //bind the program
    prog->bind();

    //set uniform data
    prog->setUniformData(mvpMatrix, "MVP");

    //bind the VAO
    msh.bind();

    //bind the cube map texture
    glBindTexture(GL_TEXTURE_CUBE_MAP, cubeMap);

    glDrawElements(GL_TRIANGLES, msh.getNumVerts(), GL_UNSIGNED_INT, 0); //draw

    msh.unbind(); //unbind the VAO

    prog->unbind();

    glDepthMask(GL_TRUE);

}

```

And here are the shaders:

Vertex Shader:

```
#version 330 core

in vec3 pos;

uniform mat4 MVP;

out vec3 fragTexVector;

void main()
{
    gl_Position = MVP*vec4(pos, 1);
    fragTexVector = pos;
}

```

Fragment Shader:

```
#version 330 core

out vec4 finalColor;

in vec3 fragTexVector;

uniform samplerCube skybox;

void main()
{
    //finalColor = vec4(1,1,1,1);
    finalColor = texture(skybox, fragTexVector);
}

```

I have scanned over this piece of code and over my entire project many times to find what was wrong and could not find anything. The samplerCube seems to always get black pixels.

Extra Information (might be helpful, I'm not sure):

I have tried debugging the program with VOGL (Valve's opengl debugger) but when I try to capture a snapshot of a frame it crashes with an error:

```
Internal error: KTX texture failed internal consistency check, texture 7 target GL_TEXTURE_CUBE_MAP. This should not happen!

```

I'm very new to OpenGL and if anybody with OpenGL experience could help me with issue it would be greatly appreciated.

Thanks.

# Answer
> 1 votes
It turns out that the cube map texture has to be EXACTLY square or OpenGL will break, and for some reason it doesn't throw an error when I do this, so I don't really know if this is a SOIL error or OpenGL error...

EDIT: I used a different library to load textures and it seems that the texture still is black when its is not perfectly square.

---
Tags: opengl, c++, 3d, textures, graphics
---