# Question
Title: How do you know when you are ready for game programming?
I've been programming for a while now and I want to make games or game engines. But I don't really know how much of programming one does need to learn to have the proper knowledge to make games. My question is, how hard it it really ? And what is the proper knowledge of programming when you're getting started ?

I've programmed mostly in C#, Java and C++.

# Answer
You can basically start leaning to program by making games. To learn game-specific programming knowledge you must make games. There is no grand preparation ceremony you must complete before you can make games.

Like any other skill, it's all just practice and repetition. Make games. Make lots of little games.

Don't start with a big project or grand idea. Start with Pong, move on to Tetris, etc.
> 1 votes

---
Tags: c#, c++, java
---


title: How to capture video of my mobile game?

text:
# Question
Title: How to capture video of my mobile game?
I've been keeping a blog for my current Android game and as I get closer to an actual playable version of the game, screenshots just aren’t enough to show new progress anymore. What I need is video. The problem is, my game won’t run on the current emulator (uses OpenGL ES 2.0), and my computer couldn’t run the emulator if it wanted to anyways. So desktop video capture is out of the question. The only real idea I have is holding the phone in front of the only video camera I own: a webcam… yeah. Does anyone know a better (preferably free) way to capture video from an Android device?

# Answer
> 4 votes
Perhaps something like Droid@Screen would work? Here's a video of setting it up and capturing video using CamStudio. Droid@Screen is in alpha, so it *might* work. Good luck! I'll keep an eye out for those videos on your blog .)

Hopefully your computer can handle that much :/

If your android device is rooted, there's an entirely on the phone option with **ScreenCast & Recorder**. Here's an article and the android market page for paid and free. Free version limits to 30 seconds of recording.

# Answer
> 3 votes
I'm not familiar with Android development, but I've used this technique on other platforms.

As you can take screen shots, could you simply lock your time step to say 1/30th sec (instead of using actual elapsed time) and save a screen shot every frame, which you can reassemble afterwards into a video on your PC.

The main downside of that method is that audio capture is more difficult - you will probably need to recreate it or replace it with something else.

It's also helps if you can record and replay any required user inputs since the game will be running in slow motion thanks to the screen shot saving.

# Answer
> 2 votes
I know this question is a little old but Android has changed some in the past 3 years so I think it's worth posting this answer.

Starting in Android 4.4, there's native screen recording. You can use ADB from a computer the phone is connected to or there are at least a dozen or so apps to help you do it (some with root, some without).

**Without root**, you'll be able to record the screen. I don't think you can get ANY of your phones audio if you don't have root. However, I've found a 3.5mm to 3.5mm cord can connect my phone's headphone jack to my laptop's mic jack and Audacity can record the audio just fine. My favorite app for screen recording is Lollipop Screen Recorder (and I have tested it all the way out to Marshmallow, it works great). Here's a video produced with this exact setup and what it looks/sounds like. I'm a crappy youtuber, but let this stand as hopefully a victory for the setup.

**With root**, you should be able to find an app that can record the screen and any audio produced by your device without any additional cords or computers. I have less experience with these apps so I can't make a good recommendation although I think Shou.tv should be able to do this. Shou.tv can also stream if that's something you want to do.

I am not a developer of any apps or games mentioned or linked to. Also, for the record, all of this software is free. An 8 foot cable for you headphone/mic jack connection can run $12 but is really useful to have on hand for more than just this task.

# Answer
> 0 votes
Unfortunately, I don't know if there are any good, solid, simple answers, since a lot of it depends on the device you're using and the game itself. A quick google of `android video capture` turns up some info on media and video recording, some of the top results are here

This issue is that some of these solutions might take too long to implement, or plain old won't work for OpenGL games. And none of these will really show off any elements of the game that rely on touch, or accelerometer, or microphone/camera. So in some cases, the best option is to just stick the phone on a flat, well lit surface, point a camera at it, and play your game. In some cases, a web cam might be good enough to show the game in action, and you can entice people with pretty screenshots as well. If the web cam really is terrible, there's the option of finding a friend with a camera you can borrow for a few hours (or less)

# Answer
> 0 votes
This isn't the easiest way, but it doesn't require rooting your phone. You can slow down your game, run it in the emulator, record a video of the emulator, and then speed up the video. More details on http://www.firedroid.net/2010/07/01/recording-android-games/

# Answer
> 0 votes
we now have a free SDK that allows you to record videos with no overhead (we capture all the OpenGL calls) within any app or game.

And any Android game developer that sends us their video could be featured at Game Developers Conference in San Francisco

Details: http://www.lunarg.com/seemegaming/

# Answer
> 0 votes
This has been brought up but if you are serious about recording videos of your game, one of the most time and quality efficient paths is to get a 60$ hdmi recorder and an hdmi output cable. You get both sound and video in your devices native quality and you save a bunch of time.

Another cheaper option is sending a demo of your game to someone who has an hdmi recorder and asking them to kindly record a video of your game.

You should be able to record gameplay hdmi output with a compatible device like this, hdmi recorder. What you won't be able to do (probably as it's illegal) is record TV shows because the ouput is often encrypted.

So if you care about quality and framerate, getting the right hardware or asking someone who has it would be an option you could consider which may yield preferable results to software solutions.

# Answer
> -2 votes
You can use kamcord to record video or game in phone. See detail in https://www.kamcord.com/

# Answer
> -3 votes
You should port your game on Desktop. OpenGL ES 2.0 can be easily port on OpenGL 2.1. With a desktop version, you can use many tools to debug and profile your OpenGL code. Yes, it is a lot of work but you will develop quicker with a Desktop port. If you refuse to port your OpenGL ES code, there are OpenGL ES emulator on windows too (Theren't android emulators).

http://lwjgl.org/

Note: With a video capture tool, you can't expect 30FPS. Only hdmi output present on many devices can help you...

Note 2: an OGLES 2.0 android emulator with hardware support is in the google labs, but no availability date.

---
Tags: android, marketing, video
---


title: How can I show slow motion?

text:
# Question
Title: How can I show slow motion?
In my very, *very* simple 2D game I'm working on, I'd like there to be moments of slo-mo.

What is the best method of showing the player that the game is currently in slow-motion? As in, what is the most typical and obvious method used by most current games where slow-motion is a feature?

I'm fairly new to game development, and even newer to this site, so am looking for an answer which contains, basically, just bullets of things which should be different between real-time and slow-motion-time.

"Best," to avoid opinionated answers, means established and recognized, common methods of demonstrating slow-mo.

# Answer
**Music**

Unsurprisingly, slowing down the music currently playing will immediately let the player know the game has slowed down. Alternatively, you can play completely different music to indicate a change in the game's pace, or even play no music at all.

A common way to complement changes in music is to play a transition sound to ease into it rather than change soundtracks on a dime. Imagine something like one of these sounds. (Maybe itself even played at a slower or slowing speed.)

**Sound Effects**

Most likely you'll want to slow these down as well. Also consider adding reverb if you want some sounds to linger for longer.

**Motion Blur**

As mentioned in another answer, motion blur can be effective to show slowdown stylishly. But be weary of applying it to every moving object. If the screen is busy, this would create more noise, which may or may not be what you're looking for. Seen here, GTA V only applies motion blur to the car's tail lights.

**Screen Filters**

As also seen from GTA V, slow motion is accompanied by a changing of the tone of the game's colors. Desaturating the colors creates a more mellow vibe that complements a slow-down.

**View Focus**

This is more game dependent, but if you're slowing down the game so the player can more easily accomplish a task that requires careful maneuvering, consider zooming in to the area where the player needs to focus. Viewtiful Joe is an example of a modest application of zoom, but the effect is notable.

GTA V doesn't change the camera view at all, but it does add a vignette effect which focuses the player on the car by fading out the screen's edges.
> 4 votes

---
Tags: game-mechanics, user-experience
---


title: Create a 2D trail in Unity?

text:
# Question
Title: Create a 2D trail in Unity?
I would like to make a trail for a pixelated snake such as this one :

As you can see, the cross simply repeats itself to create the snake. In Unity I have messed around with Trail Renderer, tried everything to import the cross as a texture / sprite, then created all sorts of materials for it, but it just won't work the same way.

How can I achieve this effect please? Thanks!

# Answer
I am afraid that the effect which you desire won't be able to achieve through Trail renderer. I had once accidentally achieved it while playing with multiple cameras. What you need is to stop the camera from clearing the render buffer before drawing a new frame. So that the cross at last position remains as is and the new cross gets drawn on top of it . This doesn't affects the draw calls or performance, as it is just refraining the buffer from clearing. You need to play around with Clear Flags settings for camera , and set it to don't clear.
> 1 votes

# Answer
ONE method could be using an object with a particle system. Manage the particle system the right way , controlling it by script, spamming ONE particle based on object moviments. Use the cross ad particle texture..
> 0 votes

---
Tags: unity, c#, trail-renderer
---


# Question
Title: What caused rotation in exported blender model to jMonkey? (OGRE)
First off, I am very new to jMonkeyEngine 3 and still learning. Not exactly sure what could be causing my snowman to have already been rotated before import. I created him in blender and it was facing forward. The up axis was Z and the forward axis was Y.

For some reason when it is imported into jMonkey I got it pre-rotated which is not what I wanted nor what I coded. I just imported like this tutorial says to do in the book.

Exported as ORGE \> Converted to .j3o \> Imported with code.

```
snowMan = assetManager.loadModel("Models/Snowman/snowman.j3o");
Material matVC = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
matVC.setBoolean("VertexColor", true);
snowMan.setMaterial(matVC);
rootNode.attachChild(snowMan);

```

**What should I look at doing to try and remedy this? Not even sure where to start. Could it be messed up in blender? The way I exported? jMonkey?**

**Update #1:** *I think it has to do with either the exporter or something I did in blender... not sure what though. Pretty sure it is not the fault of jMonkey.*

Now it looks like this.

# Answer
Issue is the the OGRE exporter and will be contacted soon about issue.

Recommend to use .obj with UV Mapping instead since it does not support vertex coloring.
> 0 votes

# Answer
That's a left vs right hand coordinate system. It's actually not a rotation but a reflection. It seems that blender uses a right hand coordinate system and jMonkeyEngine or Ogre use left hand coordinate system. If you want to convert between the two system check this detailed paper, with the simplest solution being to flip the actual Z direction.

Also here is a related SO question.
> 0 votes

# Answer
I know this is an old thread, but I just had this same problem and got it fixed, so..

Select your snowman in blender and press alt+R to clear rotation. Now it's probably going to look the same as in jMonkey. Apparently the ogre exporter doesn't apply rotations you made to the object.

To fix this, apply the rotation permanently to the snowman in blender: from the object menu -\> apply -\> rotation. Now it should load fine in jMonkey.
> 0 votes

---
Tags: java, blender, jmonkeyengine
---


# Question
Title: How can shader code duplication be reduced in Unity?
In our current Unity project we have a few shaders that are basically just supersets of another shader. For example, we have a shader that performs lighting calculates with diffuse, normal, specular, and gloss maps, and a shader that performs lighting calculations with a diffuse, normal, specular, gloss, and glow map. The first is a subset of the second, but for performance reasons we've decided to separate them. This leaves us with heaps of duplicated code.

On top of this, I need to add stencil buffer operations to some of these materials, which is about 3 lines, but from what I can see, requires the entire shader file to be copied again.

How can we reduce this code duplication? In an object orientated language we'd used inheritence and polymorphism. What can we do here?

# Answer
You can use #include files in your shader source files, this is described here.

So like this you can regroup any common code into functions, which you put in an include file.
> 5 votes

---
Tags: unity, shaders
---


# Question
Title: How can I create a parabola that does not use negative X coordinates
I am currently devloping my first javascript program ever which is a table tennis game. I am trying to create trajectory for the ball to follow when hit - just a very basic parabola. However im not very good at math, and I have no idea how to do this!

I want to have the parabola start wherever the ball was hit. The X position will be either 100 or 110, since that is the only two positions where it is possible to hit the ball. And the Y position will completely vary. So I need to create a parabola that - if your looking at a 2D table - starts from the right side of the net and ends up on the right side, as if you did an under arm hit. I have no ides how to do this since there will be no minus positions! \- Maybe I should have two arcs one coming up and the other one coming down? I also have no idea what equation would make an trajectory in the shape of an arc.

# Answer
> 2 votes
You don't necessarily need a parabola formula for this.
The best way, in my opinion, to do this is to update the velocity of the ball each frame. I don't know how you organized your code, but I assume you have an update function that is executed multiples times per frame.

To make the trajectory of a parabola, you simply need to substract a constant to the velocity each frame.

```
ball.velocity.y = -1; // The initial velocity of the ball, negative because it is going upward
ball.velocity.x = 1; // The constant velocity of the ball on the X axis

var gravity = 9.81; // The acceleration due to gravity

function update(){

    ball.velocity.y += gravity; // Notice the + sign because the gravity goes downward

    // Process the velocity
    ball.position.x += ball.velocity.x;
    ball.position.y += ball.velocity.y;

}

```

I didn't include it in this snippet, but you should use a delta-time variable to handle FPS-variation (you can look it up on Google)

---
Tags: mathematics, javascript, trajectory
---


title: problems with imported texture

text:
# Question
Title: problems with imported texture
I have done a texture in GIMP and imported it in Unity but for some reason the texture appears to be squashed in the sides.

Image done in gimp:

And here is what happens in Unity:

# Answer
If you want to use it as sprite then change the import settings 'Texture Type' to 'Sprite(2D and UI)'. This will bring it back to its original dimensions. If you want to use it as texture then this wont matter, the texture depends upon the 3d object UV mapping, so it will scale properly.

For particle you can convert the entire image to have square dimensions. Like this:-
> 2 votes

---
Tags: unity, textures, import, gimp
---


title: Find alternate shortest paths in Unity

text:
# Question
Title: Find alternate shortest paths in Unity
I'm developing a game in Unity. It's a simple game where the rocket has to reach the point where the player touches on the screen. The movement of the rocket is physics based. When the rocket goes off screen on right side, it appears on left side and when it goes off on left side, it appears on right side. Similar for vertical axis.

In the picture above, the user touches on the bottom right corner. The rocket could either rotate and go there (Path 1) or it would directly go up left off the screen and appear on bottom right corner and reach there(Path 2). I want to implement the Path 2. How would it calculate the distances and determine the shorter path and then proceed in that direction?

# Answer
Euclidean distante = sqrt (dx * dx + dy * dy), for your distance you need to define dx as min(abs(x2-x1),screenwidth-abs(x2-x1)) same thing for dy.

Usualy the direction vector is Pt - Pm (Position vector target - Position vector missile). In your case you can define Direction vector x component as

```
if (x2-x1)>=0
  if (abs(x2-x1) < abs((x2-x1)-width))
    DirX = x2-x1;
  else
    DirX = (x2-x1)-width;
else
  if (abs(x2-x1) < abs(width + (x2-x1))
    DirX=x2-x1;
  else
    DirX= width + (x2-x1);

```

In the same way (using HEIGTH) you can get DirY.
> 2 votes

---
Tags: unity, 2d, physics, path
---


title: Delete EdgeCollider issue

text:
# Question
Title: Delete EdgeCollider issue
In this program, When i draw a hill, a car can road on it's surface, and when I draw another one, the previous hill should remove.

but unfortunately the previous edge collider looks still there. this is what i've done for delete this collider :

```
        if(col)
        {
            col.Reset();
            col = null;
            Destroy(col);
        }

```

unfortunately nothing works :) `col.enabled = false` is also doesn't work

this is the code: i don't know what i have to do to disable the previous collision

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

public class LineFreeDraw : MonoBehaviour
{
    private LineRenderer line;
    private EdgeCollider2D col;
    private bool isMousePressed;
    private List<Vector2> pointsList;
    private Vector2[] pointsArray;
    private Vector3 mousePos;

    // Structure for line points
    struct myLine
    {
        public Vector3 StartPoint;
        public Vector3 EndPoint;
    };
    //  -----------------------------------
    void Awake()
    {
        // Create line renderer component and set its property
        line = new GameObject("Line").AddComponent<LineRenderer>();
        line.material = new Material(Shader.Find("Particles/Additive"));
        line.SetVertexCount(0);
        line.SetWidth(0.9f, 0.9f);
        line.SetColors(Color.green, Color.green);
        line.useWorldSpace = true;
        isMousePressed = false;
        pointsList = new List<Vector2>();
    }
    //  -----------------------------------
    void Update()
    {
        // If mouse button down, remove old line and set its color to green
        if (Input.GetMouseButtonDown(0))
        {
            if(col)
            {
                col.Reset();
                col = null;
                Destroy(col);
            }

            isMousePressed = true;
            line.SetVertexCount(0);
            pointsList.RemoveRange(0, pointsList.Count);
            line.SetColors(Color.green, Color.green);
        }
        else if (Input.GetMouseButtonUp(0))
        {
            isMousePressed = false;
        }
        // Drawing line when mouse is moving(presses)
        if (isMousePressed)
        {
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            if (!pointsList.Contains(mousePos))
            {
                pointsList.Add(new Vector2(mousePos.x, mousePos.y));

                line.SetVertexCount(pointsList.Count);
                line.SetPosition(pointsList.Count - 1, (Vector3)pointsList[pointsList.Count - 1]);

                CarIsCollide();
            }
        }
    }

    private void CarIsCollide()
    {

        col = new GameObject("Collider").AddComponent<EdgeCollider2D>();

        // Collider is added as child object of line
        col.transform.parent = line.transform;

        if (pointsList.Count < 2)
            return;

        pointsArray = new Vector2[] { pointsList[pointsList.Count - 2], pointsList[pointsList.Count - 1] };
            col.points = pointsArray;

    }

}

```

# Answer
> 0 votes
Your code enters multiple Edge colliders and in the if loop only destroys the latest collider object.Check the following image, the collider of previous line still exist as child of the line game object

We need to delete each and every child in the Mouse button down event , which will fix the issue.

```
 if (Input.GetMouseButtonDown(0))
        {
            if(col)
            {
                col=null;

            }

            foreach (Transform child in line.transform)
            {
                GameObject.Destroy(child.gameObject);
            }

            isMousePressed = true;
            line.SetVertexCount(0);
            pointsList.RemoveRange(0, pointsList.Count);
            line.SetColors(Color.green, Color.green);
        }

```

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


title: What format should I choose?

text:
# Question
Title: What format should I choose?
I am making models in blender to export them then in unity, and unity can import .blend formats as well as .fbx, so which one is better, is there even any difference.

# Answer
I would suggest using fbx. It is much more widely supported by other tools and that generally means that even in Unity, more effort will have been spent on making sure that fbx works properly. If you need to import your models to other tools besides Unity for processing etc, you will probably need fbx anyhow. Also, if you decide to use some other modelling program besides blender in the future, then it will be easier to migrate them.

There is no real advantage to using blend files, unless you are planning to use blender specific features, which are not going to be available in other programs.

PS. The one advantage of using blend files in unity is for speed and convenience during development, but I would still convert them to fbx when they are finalized.
> 3 votes

# Answer
Usually FBX is preferred for exporting the models. You can follow this link for more info. http://docs.unity3d.com/Manual/HOWTO-ImportObjectBlender.html
> 1 votes

---
Tags: unity, file-format
---


# Question
Title: How do you get the player's last car in GTA IV?
I am developing a car control plugin for GTA IV and everything is working except the lock/unlock doors feature.

Despite using the `Player.LastVehicle` handle, the code only works while the player is **in** the car. How can I get the code to work when the player is inside **or** outside the car?

Here's what I have so far:

```
'Lock/Unlock
        If e.Key = Keys.OemPipe AndAlso e.Control Then
            'Lock Codes: 1 - Unlocked; 2 - Locked (Player & NPCs); 3 - Locked (Player); 4 - Locked (Player, Inside); 7 - Locked (Can Break Into)
            If DoorLock = False Then
                Player.LastVehicle.HazardLightsOn = True
                Wait(1000)
                Player.LastVehicle.HazardLightsOn = False
                Native.Function.Call("LOCK_CAR_DOORS", Player.LastVehicle, 2)
                DoorLock = True
                Game.DisplayText("Vehicle Locked")
            Else
                Player.LastVehicle.HazardLightsOn = True
                Wait(2000)
                Player.LastVehicle.HazardLightsOn = False
                Native.Function.Call("LOCK_CAR_DOORS", Player.LastVehicle, 1)
                DoorLock = False
                Game.DisplayText("Vehicle Unlocked")
            End If
        End If

```

# Answer
> 1 votes
I've never worked with GTA mods but assuming that if you can't actually get LastVehicle when outside of the car (which seems unintuitive to me, given the name) my guess would be to track the last vehicle yourself. When the player is in the car, store LastVehicle as a variable. Then you can refer to it whenever you want.

Update (how to store LastVehicle as a variable):

It's been a while since I did any VB coding and as I said, I've never done any GTA modding so this is just a guess but hopefully I'm not too far off...

```
Private lastVehicle As Vehicle
If (Not Player.LastVehicle Is Nothing) Then
    lastVehicle = Player.LastVehicle
End If

```

---
Tags: plugin, vb.net
---


# Question
Title: Changing long float to number + short scale
I am looking to use a piece of code to take an extremely long number and convert it to decimal equivalent + short scale. (i.e. 120100000000 would be 120.1 Billion)

I am doing this with two separate scripts but this can be condensed into a single one. I am trying to look for a recurring process instead of the massive amount of if statements currently running in the script. This is being done with an external array in Unity that holds the strings for short scale. (billion,trillion, etc)

Trying to find a recurring model that will look for the length, and attach it to the appropriate array object.

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

public class amountText : MonoBehaviour {
    public Text text;
    public Text numberPref;
    public string[] values;
    public static float number = 1000f;

    private float numberLength;
    private float remainder;
    private float increaseAmount = 5000f;

void Start () {
    text = GetComponent <Text>();
}
void Update () {
    text.text = Mathf.RoundToInt(number).ToString();
    numberLength =  Mathf.RoundToInt(number).ToString().Length;
    if(numberLength <9) {
        text.text = Mathf.RountToInt(number).ToString();
        numberPref.text = (" ");
    }
    if(numberLength > 9 && numberLength =< 12) {
        text.text = number/1E-9;
        numberPref.text = (values[0]);
    }
    if(numberLength > 12 && numberLength =< 15) {
        text.text = number/1E-12;
        numberPref.text = (values[1]);
    }
    if(numberLength > 15 && numberLength =< 18) {
        text.text = number/1E-15;
        numberPref.text = (values[2]);
    }

}
}

```

# Answer
> 1 votes
I would make only minor changes to your code:

```
private const string[] _postfixes = { "billion", ... };
public static string BigNumberToString(double number)
{
  int exponent = 0;
  double num = number;
  while(num > 1000.0)
  {
    exponent ++;
    num /= 1000.0;
  }
  //additional logic for converting here, for your example
  if(exponent < 3)
    return number.ToString();
  else
    return num.ToString() + _postfixes[exponent - 3];
}

```

The while cycle is effectively the same like yours `Mathf.RoundToInt(number).ToString().Length;` and feel free to replace it if you don't need to parse numbers above int.MaxValue (the remainder would be `exponent - (exponent % 3)`). `exponent - 3` because you are not interested in naming numbers below 1.0E+09, providing you direct index in your posfix array. You might also consider adding some error checking. Also please note I did not check the syntax.
*sorry for the edits, it was not so straight-forward to implement as I thought*

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


# Question
Title: OpenGL, GLSL, Modify Background Fill via Fragment Shader
I have noticed that fragments rendered by the `glClearColor()` method do not pass through shaders. However, I'd like to modify these fragments using my fragment shader. Is there any way of forcing them through?

To clarify, I'd like to fill the background with a solid colour in such a way that causes each pixel to be treated as a fragment (and passed through the fragment shader).

One way of doing this is creating and loading an image into memory that is as large as the background. However, this seems like a horrible waste of memory.

I have tried making a VAO with a source size of one pixel and destination size of the screen dimensions but this gets treated as a single fragment.

# Answer
> 2 votes
> ```
> One way of doing this is creating and loading an image
> into memory that is as large as the background. However,
> this seems like a horrible waste of memory.
>
> ```

To affect the whole screen with a fragment shader you don't need a full-screen texture, just a full-screen polygon (one quad or two triangles). The four vertices would have attributes on them. At the least, you need XY coordinate (so the vertex shader knows where to put the four corners). The fragment shader could also use the XY coordinate to influence the fragment shader. (Otherwise, the fragment shader would only be able to draw a solid color, having no way to treat each fragment uniquely.)

The geometry would have XY attributes spanning (-1,-1) to (+1,+1). The vertex shader will be trivial, something like:

```
#version 410
in vec2 xy;
out vec2 xyVarying;
void main(void)
{
    float z = 0.0; // middle
    gl_Position = vec4(xy.x, xy.y, z, 1.0);
    xyVarying = xy;
}

```

And then the fragment shader can do whatever you like with the varying XY coordinate. For example:

```
#version 410

in vec2 xyVarying;

out vec4 fragColor;
void main (void)
{
    // map (-1,-1)(+1,+1) to red-green ramps.
    fragColor = vec4(xyVarying.x / 2.0 + 0.5,
                     xyVarying.y / 2.0 + 0.5,
                     0.0 ,1.0);
}

```

Hope that helps!

# Answer
> 1 votes
If you are just filling with a solid color then you could pass that color to the fragment shader as a uniform, and process it from there. Use a full screen quad for the fragment shader to render onto.

Another way is to this to render the background to an FBO and do the full screen quad trick but apply the FBO texture to it. This would be very memory inefficient though as you have to pass that texture to the GPU.

# Answer
> 0 votes
I suggest you make a skybox: A skybox is a large cube which you render around your camera which will give you the ability to pass each pixel through a fragment shader. And you can render anything onto the skybox: a color, an image, a gradient, etc.

Just be sure to call `glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);`

A good tutorial on this topic is this one: http://antongerdelan.net/opengl/cubemaps.html

edit: Also make sure you render your skybox before everything else otherwise it'll hide all the objects in your scene.

---
Tags: opengl, java, glsl, lwjgl, fragment-shader
---


# Question
Title: Why does my rectangle move faster in one direction than in the opposite?
I am using Slick2d to create a top-down game, however an rectangle than I am drawing to the display is moving faster to the left than to the right, and faster up than down.

I am updating frames like so:

```
public void update(GameContainer gameContainer, int delta) throws SlickException {
    player = new Rectangle(playerX, playerY, 10, 20);

    if (gameContainer.getInput().isKeyDown(Input.KEY_LEFT)) {
        x -= delta * 0.1f;
    }
    if (gameContainer.getInput().isKeyDown(Input.KEY_RIGHT)) {
        x += delta * 0.1f;
    }
    if (gameContainer.getInput().isKeyDown(Input.KEY_UP)) {
        y -= delta * 0.1f;
    }
    if (gameContainer.getInput().isKeyDown(Input.KEY_DOWN)) {
        y += delta * 0.1f;
    }
}

```

I then simply draw the rectangle to the display. It is noteworthy that the rectangle class is a`org.newdawn.slick.geom.Rectangle`.

Why are the speeds for the movement different, and how can I fix this?

***EDIT:*** I have fixed the problem by slowing the movement to the left and up, but this does not explain why the problem occurs

# Answer
> 2 votes
This is most likely a rounding error. I'm guessing that x and y are ints.

Keeping track of the x and y values as floats, I expect will fix the issue.

Consider if the values are being floored:

Moving Left `10 - 1.6 = 8`

Moving Right `10 + 1.6 = 11`

---
Tags: java, slick
---


title: Creating my own kill cam

text:
# Question
Title: Creating my own kill cam
I plan on creating my own kill cam system for a sandbox tool set. After thinking about the mechanics of the kill cam itself, however, I'm quite lost. I'm trying to recreate the ones commonly seen in call of duty games that show, from the view of the killer, the actual killing scene.

**My Thoughts:**

-I can't just keep in memory when people kill others because I wouldn't know when to start the 'recording process'. There is on way for me to accurately determine when somebody is 'about' to kill someone.

-My only real idea so far is to have a complete duplicate of everything loaded off to the side copying all the movement from the original world but with a 10 second delay. That way, all the kill cams would be 10 seconds long and the persons camera would just be moved to the second world of their killer.

**My Questions:**

Is there already an accepted way to do this? Does anybody have any good ideas for something like this? Thanks if you can!

# Answer
Store the last few seconds of movement data of **relevant dynamic objects**.

This data should be complete enough that it can be used to reconstruct a killcam scene if necessary, but incomplete enough that you can afford retrieving and storing at short enough intervals.

Examples of things you may want to track:

* Which way a visible player is moving/looking
* Whether killer is zoomed in on gun scope

Things you probably want to optimise out:

* Data about players whom the killer cannot see
* Anyone's actual screen output
> 11 votes

# Answer
No idea how this is normally implemented, but you could have each bullet save a clip from the time it is fired, to when it hits a target. If the shooting is done just with a hitscan, you can compute whether or not to generate the kill cam footage in the same cycle when you perform the hitscan.
> 0 votes

# Answer
You can save an object's transform every couple seconds or so. Do this for all applicable dynamic objects. Stagger the saving such that each frame you are only saving a couple matrices. save as far back in time as you like.

During replay, You actually use these transforms in a rendering engine to animate through a scene, interpolating between transforms by time for each frame as necessary.

It is not an exact duplicate but very very close & it allows you to give the player the option of camera control during replay so they can choose where to view the scene from.
> 0 votes

# Answer
you can implement some replay feature in your game. using replay function, killcam is just a replay being played from some specific gametime, and from some player's point of veiw. later you can save replays and let others review games after they're finished.

also your idea to run a same game with inputs by 10sec delay is a good approach if your game doesn't consume high computational power.
> 0 votes

# Answer
How about this...

Only record when there is a possibility of killing.

Think about it from an AIM-BOT's perspective. It will only aim/fire when killing is a possibility. So you should only record when an enemy is within killable/visible range.
> 0 votes

# Answer
Set a radius around the player and if another player enters the radius then it starts screen recording for both people. You then wait to see if anyone is killed. If so then you find the killer and take their recording and rewind the amount of time elapsed since the kill plus the length you want the video to be and rewind and play it for the one who was killed. If nobody is killed and nobody else is in the radius around the character then delete or stop the recording. If the killer is zoomed in on a scope then cast a ray to where he is aiming and create another trigger radius. If someone is in it then it records the screen of whoever is in the radius where the aiming character is aiming and of the character aiming. If someone dies by the character aiming then you take the time elapsed since the kill plus the length you want the kill cam to be and you rewind and play this for the one who was killed. If they zoom out then stop the recording. This is a concept so i havent tried it.
> 0 votes

---
Tags: camera
---


# Question
Title: How to avoid lots of ugly math code and constants-hoarding?
In a lot of the games I've (tried) making in the past, I often run into the problem of the code getting really heavy on ugly mathematical code. This happens especially frequently in setting up user-interfaces such as choosing the positions of things on screen. Just to get an idea of what I mean, here is some code from the setup for the level selection screen in a recent project:

It gets really verbose, as you can probably tell. I try to mitigate it with descriptive variable names and detailed explanations of the purposes of constants such as `INITIAL_LEVEL_SELECT_Y_OFFSET`, but then it becomes verbose just in a different way.

I considered making everything, `rowNum`, `totalWidth`, `totalHeight`, etc., constants, but to me it looked really weird to have 30+ constants attached to every class. I also tried using local variables with smaller names, such as `xOffset` and `yOffset`, but then it defeats the purpose of having descriptive variable names (as you can see I use `INITIAL_LEVEL_SELECT_Y_OFFSET` anyways 5 lines after declaring `yOffset`).

Another problem this causes is that some constants are used by multiple classes, but aren't really general enough to be included in some static "Constants" class. For example, the constructor for `LevelSelectButton` uses `INITIAL_LEVEL_SELECT_X_OFFSET`, and the class in the picture above does the reverse and uses a constant defined in `LevelSelectButton`.

I originally placed the constants according to "what they were most attached to" if that makes any sense. For example, `BUTTON_WIDTH` makes most sense in the `LevelSelectButton` class since it describes a level select button's width.

Another problem is that some of these constants refer to the width and height of images that haven't been loaded statically. For example, `LevelSelectButton.BUTTON_WIDTH` is supposed to be the same as the width of the button sprite that class uses, but my current setup requires that the sprite for `LevelSelectButton` be loaded in the constructor for that class (I can think of ways to remedy this based on my current system however).

Any tips on how to avoid these problems? More comments? More constants? Less constants? A static `Constants` class?

# Answer
I'd move all those UI constants to a centralized file. It doesn't matter if they are only used in one class or not. The reason is that if you ever want to adjust that type of stuff, it is nice to have it all in one location. You don't want to have to muck with a dozen different classes just because you decided you wanted to change the overall look and feel of your UI.

Make a `LookAndFeel` static class (or some similarly descriptive name) to contain all those types of UI properties and constants. You might also want to have nested classes within your LookAndFeel class to namespace and categorize all your constants and properties, rather than having very verbose constant names.

Namespacing is particularly nice if you have code completion or intellisense like in Visual Studio. Then you don't have to remember all those long names and if you have documented your code, you can get descriptions for that stuff as you write.

Also, don't be afraid to use functions to self-document and contain your code bits. It doesn't matter if it's only used once. It won't really hurt performance at all and will make your code more organized.
> 4 votes

---
Tags: c#, monogame, architecture
---


# Question
Title: Generic multiple containers derived classes for Entity System
I am working on an entity system for a game. I have read that cache is very important with the common operation of iterating over entities and their components.

Currently I have a class World that contains the list of entities, and a list of each component.

```
class World {
  vector<Entity> entities;
  vector<PositionComponent> position_components;
  vector<SpeedComponent> speed_components;
  ...
};

```

The idea of this, is to have entities and components contiguous in memory to be cache-friendly.

The problem is that you have to write specific code for each different component, as it is hardcoded in the source code. One solution could be to have a matrix of Component\*, where the i-th row of the matrix are all PositionComponents, and so on. The problem with this, is that with the pointers you don't have the memory continuous and break with the cache-friendly.

What would the best way to write generic code and still have cache-friendly data?

# Answer
> 1 votes
The main purpose of the ECS pattern is to be programmer friendly, not speed. So this is essentially an architecture problem, although I will also address your cache-friendliness concerns.

It seems like you're setting your components up like data records, whereas they should contain all the relevant behavior for their subject. Think

* PhysicsComponent
* SpriteComponent
* SoundEmitterComponent

Rather than

* SpeedComponent
* PositionComponent
* RotationComponent

Thus, your component container should be the abstract "Component" type. Behavior specific to each component should be contained entirely within the specific component class.

The more important thing to cache friendliness is combining components that need each other's data. Position and speed will usually be accessed very close to each other. Same with position and, say, rotation. So put them all that data in a physics component *with the physics behavior*. So rather than trying to optimize *all* the components in aggregate, focus on the actual function of each component. Basically, assume the cache will be wiped between each component update and structure your data accordingly.

---
Tags: c++, entity-system, entity-component
---


title: Unity5 How to create a floor

text:
# Question
Title: Unity5 How to create a floor
This may be a may be a very basic question but I have a 32x32 tile of grass for a 2D platformer I'm making. Is there an easy way to duplicate the tiles and lay them out? or will I have to copy and paste the tile a 100 times and adjust each one individually just to make a level?

# Answer
Hey I have answered a similar question , where you can populate different tiles as per need, using a 2d matrix to hold the information. Its very basic but you can build on top of it , to suit your needs :)

Link:- Generate static 2D Tilemap from array
> 1 votes

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


# Question
Title: Unity5 I lost my codes inside .cs file. C# files still exist, but codes gone
Unity 5.1.2f1 (64-bit) version.(windows 8.1) I closed Unity. After a while ago I opened Unity and I had some errors in Console.Then I clicked the error and I realized that I lost my code in some of my C# files.Then I checked folders of my scripts and I checked date modified section of my C# files.

Here is image of my problem.

as you can see, some of file's modified date is in 7th month and other's modified date is in 8th date. Problem is I just saved those file's (7th month) just couple of days.

I had this problem before as well. That time only few changes lost and I re-code those files, but not I lost hundreds lines of codes, so I can't re-code all same. Is there any way to recover those codes?

# Answer
> 1 votes
> Is there any way to recover those codes?

Short answer: No.

Long answer: Maybe. If you compiled your game, you might be able to decompile it (perhaps with something like: https://www.jetbrains.com/decompiler/ --- your actual mileage may vary). Or depending on what exactly happened to the old file(s), perhaps you can recover them if they were deleted (http://www.howtogeek.com/169344/how-to-recover-a-deleted-file-the-ultimate-guide/). Outside of that I can't think of any other options off the top of my head. The work it would take to get it back in working order from recovered files is most likely more work than just rewriting whatever was lost.

Now to address the cause of the problem; Always back everything up, and just be thankful you only lost a measly few hundred lines or so. Even if you just copy and paste files in another folder on your computer, or use git (et al) to manage your source files... you really should have a way to get back to a working state of your game when things start exploding (be it with the failed addition of new code, someone accidentallies the whole thing, or even if your hard drive decides it wants to switch careers to being a door stop).

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


# Question
Title: Colliders for moving inside a spaceship when the whole spaceship is made of a single mesh (in Unity)
*I've begun to study a unity engine in one purpose: I have a great multi player game* idea!
**The main essence:** *In space there are two (or even more) huge spaceships with crew consisted of players (all real humans). Ships are very powerful dreadnoughts with a lot of features (radar system, many weapons, missals, refinery factory, gravity generator, indoor light system, shields generators, engines and so on), but all systems are broken at the beginning of the game. Crew should decide, which systems are more important in battle and repair it. They should extract materials from asteroids and revive their spaceship. Then, they should locate second ship, and try to destroy it. Whose spaceship will be in a whole skin during one minute after destroying another, will be the winners. If there are more then two spaceships, surviving crew from destroyed ship can move to another alive ship.*
I've already draw detailed 3d model of spaceship, but I faced with a problem during importing model to unity. The problem with mesh collider. Players should get into a ship and walking in it, **HOW can I do that?** I can't use non-convex mesh collider in unity 5, and I cannot put one collider to another. It would solve the problem, if I draw ship piece by piece, but not as entire. But ship is really complex, to assembly it from prepared parts take really long time and ship will be messily. **Is there another way to solve my problem?**

# Answer
one solution may be : import models in unity without mesh collider, then manipulate your unity scene adding empty/invisible objects containing the colliders (box colliders?) you need to delimitate walls and floors.
> 0 votes

# Answer
You could try and create 3d game objects like cubes and spheres, then as those have colliders place them somehow to fit approximately the walls, the floor and ceiling and then just remove the mesh renderer component from those objects to make them invisible.
> 0 votes

# Answer
https://www.youtube.com/watch?v=bh9ArKrPY8w

You have options. You can either use a bunch of primitive colliders (which will be most efficient but also the most time consuming and tedious option), or you can use a simplified mesh created specifically created to be used as a collider. The above video goes into more information about colliders and goes over these options in more detail.
> 0 votes

---
Tags: physics, rigid-body-dynamics, unity, meshcollider
---


# Question
Title: Why do my game objects jitter when moving the camera?
I'm moving from Qt Widgets' `QGraphicsScene` to Qt Quick's `QQuickItem` for rendering my game objects. One of the things this involves is setting up a scene and the view onto that scene, as this was previously managed by `QGraphicsScene` and `QGraphicsView`.

My naive attempt was to do the following:

```
void SceneView::centerOn(const QPointF &pos)
{
    if (mScene) {
        mScene->setX(-(pos.x() - width() / 2));
        mScene->setY(-(pos.y() - height() / 2));
    }
}

```

This works, but it produces this odd effect where some game objects "jump around" between neighbouring pixels while the camera comes to a halt while following the player:

The player's movement is fine. The crate also does not seem to exhibit this problem (though its Box2D debug drawing marker does).

This is what it looks like when the player moves without the camera following it:

This is what I'd expect from the other game objects when the camera is moving; no movement whatsoever relative to the scene.

The old, correct movement looked like this:

The old code:

```
void MapView::centerOverFollowedItem()
{
    QRectF geometry(mFollowing->pos(), mFollowing->boundingRect().size());
    centerOn(geometry.center());
}

```

(QGraphicsView::centerOn implementation)

What could be causing this?

# Answer
Ok, that's awkward. My last edit revealed the answer to my problem (that I've been struggling with all day): `QGraphicsView` casts the camera x/y position to integers...

This is the solution:

```
void SceneView::centerOn(const QPointF &pos)
{
    if (mScene) {
        mScene->setX(int(-(pos.x() - width() / 2)));
        mScene->setY(int(-(pos.y() - height() / 2)));
    }
}

```
> 9 votes

---
Tags: 2d, box2d, camera, movement, qt
---


# Question
Title: How to correctly specify the offset in a call to glVertexAttribPointer()?
I'm trying to draw a simple triangle using the following vertices:

```
std::vector<VertexFormat> vertices;
vertices.push_back(VertexFormat(glm::vec3(0.25, -0.25, 0.0),
    glm::vec4(1, 0, 0, 1)));
vertices.push_back(VertexFormat(glm::vec3(-0.25, -0.25, 0.0),
    glm::vec4(0, 1, 0, 1)));
vertices.push_back(VertexFormat(glm::vec3(0.25, 0.25, 0.0),
    glm::vec4(0, 0, 1, 1)));

```

The corresponding Vertex format is given by the following struct:

```
struct VertexFormat
{
    glm::vec3 position;
    glm::vec4 color;

    VertexFormat(const glm::vec3 &iPos, const glm::vec4 &iColor)
    {
        position = iPos;
        color = iColor;
    }
};

```

The first call to `glVertexAttribPointer()` is easy since the position vector appears first in the struct, the call is as follows:

```
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0)

```

The second call to `glVertexAttribPointer()` should be made specifying a suitable offset for the color attribute of a vertex. Since the color vector appears after the position, then such offset should be given by `sizeof(glm::vec3)`. The corresponding call is:

```
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(sizeof(glm::vec3)))

```

The output of the program using these parameters is:

This output is wrong. There are only two colors (green and blue) and the colors are in the wrong position, note that the bottom-left vertex is blue, but according to the code the vertex should be green.

If the offset is changed to `sizeof(glm::vec4)` the call is:

```
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(sizeof(glm::vec4)));

```

And the triangle is rendered correctly

So, Is my understanding of the offset parameter wrong? Why using an offset with the size of a vec4 gives the right output?

Any help would be appreciated.

P.S. Sorry for the bad english.

Edit: After reading the answer of Fibbles, and the comments of Fuzz Logic, I checked the size of the VertexFormat struct. A sizeof() gives a size of 32 bytes for a 32 bit executable. So padding is indeed the problem here. Using the macro suggested by Fibbles solves the problem. Thanks for everything guys!

# Answer
> 5 votes
Your struct is likely being padded by the compiler. The only guarantee offered by a struct is that its members will be sequential in the order they are declared. Compilers are free to add as much or as little padding as they like.

C and C++ contain a handy macro for determining offsets within structs. I'd recommend using it rather than manually working out the offsets because your code will remain correct even if you later add or remove members of the struct.

```
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (GLvoid*)offsetof(VertexFormat, color));

```

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


# Question
Title: How can I send someone an early version of my game made in clickteam fusion 2.5?
I'm currently in the process of making my first game and have a pretty sturdy prototype, but I don't know how to send it out to select people. Any suggestions?

# Answer
> 2 votes
I have never used ClickTeam Fusion, but if it simply like other programs, and if this video is not outdated, you should be able to export your game and build it into either an iOS, Android, Flash, or HTML5 format.

If you are making a PC game, then Flash or HTML5 work, otherwise, you could use iOS or Android respectively.

### TO EXPORT:

* Click on `Tools` on the menu bar and make sure `Preferences > General > Exporters` is set to your preferred exporting file system, whether it be Android, iOS, Flash (SFW), or HTML5. If you're not sure go with SFW.
* If you set it to be Android, you will probably have to download the Android SDK and figure out where your JDK directory is, but a quick Google search will clear up both.
* In any case, once you are done with that and made sure all the settings are to your liking, you can proceed to click on `File` on the menu bar and head to `Build > Application` where you will then choose where to build your application. Create a folder on the desktop or wherever you want, and build it in there.
* Wait for a bit, and viola, your game has been exported.

### TO SEND TO OTHERS:

* Upload your file to a file sharing site such as Mediafire, Mega, Dropbox, or Google Drive.
* Send the person you wish to send the game to the link.
* The person downloads the file, and if it is SFW, they will have to have Flash Player to run it, otherwise, they can either run it in their typical browser (HTML5) or in their respective phones (iOS or Android).
* If you are feeling particularly open, you could always upload your code to GitHub and there anyone can download your code, or help with it's development such as editing it or fixing it. (With your consent of course).

---
Tags: distribution, clickteam-fusion
---


# Question
Title: WebGL Multiple Lights, Blending, and Render Order
I am trying to do simple forward rendering for multiple lights using additive blending in WebGL. Following advice from this SO and this one, I simply turn on blending using `glBlendFunc(GL_ONE, GL_ONE)` and `glEnable(GL_BLEND)`.

However, while this is combining the contribution from multiple lights, it is also making everything "transparent", as in the front faces of my object are blending with the back faces. I know that rendering transparent objects requires sorting the objects by depth, but this would be extremely slow in javascript, and doesn't seem to be necessary as blending should only occur when faces are at equal depth, which is something the depth test/z-buffer should be able to handle, right?

So is sorting the objects really necessary for forward rendering of multiple lights?

# Answer
I solved this with some help from Nathan Reed in the comments of this SO answer. The blend function `glBlendFunc(GL_ONE, GL_ONE)` is purely additive, and because addition is commutative, order doesn't matter. However, what does matter is to establish depth in the z-buffer through an opaque pass before doing any blending. My solution was to simply disable blending and draw a first pass with all objects colored black, and then turn blending on and draw the contribution of each light source.

Nathan Reed suggested here that it is usually done with "a z-prepass with color writes disabled, or another common way is to do ambient/directional light in a first pass with no blending, then add point/spot lights in later passes with blending". I haven't tried those yet so if anybody can contribute more details on how to do it that'd be great!
> 0 votes

# Answer
Yes,you are right. If your program needs any buffer texture to draw result(like light accumulation buffer in light pre-pass rendering),you needs to care about order of objects in scene. Because texture can store only one pixel for a fragment. It means texture can't store any data behind of an object when the texture store the data of most nearest(of course it will be calculated by depth test) object.
> 0 votes

---
Tags: lighting, webgl
---


# Question
Title: Can I export a model and texture from a terrain file built in Unity3D?
I am mostly familiar with building my level maps within unity, and have become quite use to its inbuilt terrain creator, in both generating my terrain, and spraying a texture on to it.

I am making a game using MonoGame XNA, and would like to use a terrain map I built with Unity. I would have to recover the file, however, and have not been able to find anything to support being able to, in the first place.

Can I export my terrain file with its texture, in any way, to use in XNA MonoGame?

# Answer
> 2 votes
Yes it is possible to export Unity terrain as an obj file to use in other game engines :)

Follow this Link :- TerrainObjExporter

---
Tags: unity, xna-4.0, monogame, terrain-rendering
---


title: Beginning on animations

text:
# Question
Title: Beginning on animations
I am clueless with regards to animations. I have a simple rendering engine that renders models, sprites, skyboxes and whatnot; but everything is simply static with no animations whatsoever. With my engine written in C++ and OpenGL I will have to learn how to implement animations accordingly; but any OpenGL book or tutorial I look for doesn't explain animations. It's probably one of those topics which being so complex requires its own book or something.

Does anyone know any great resources to explain how I can `programme` animations? I'm not interested in learning how to design them, rather just the technical side of it, you know: bones and all. I would also welcome tips as to the general concept of modern animations in OpenGL. If it also means much, I use assimp as my model loader. Suffice it to say, how does a programmer animate a model to 'run' or 'jump'?

# Answer
I found this tutorial on the OpenGL wiki a month ago. It explains the basics of skeletal animations; but I hope it is good enough for what you are trying to do, if not, you can also search `skeletal animation opengl` on google, because there is much more on the opengl wiki about this topic.
> 1 votes

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


# Question
Title: Greedy Mesh generation for a voxel-based game
EDIT: I have already found my problem and fixed it (but I cant accept my own answer for another 2 days)

I'm currently making a 3D voxel-based game and now that I have started optimising some aspects of the render-engine I've come across a problem with my mesh generation.

My voxel world is divided in 16x16x16 Segments; these segments hold the blocks and some more data which helps me to decide if the segment is visible or not. The blocks also have some data about it's visibility and a `BlockType`; the blocktype basically holds the color and some other material information about the block.

I'm currently only rendering the top, bottom, and left sides of the blocks. But somehow there is something wrong with the mesh generation whenever there are empty blocks above and next to the current block.

(In the image you are facing +x +z)

As you can see in the image above, there are rows of sticking out which shouldn't be there. (Red is what shouldn't be there)

This is my code:

```
private static HashMap<Integer, ArrayList<WorldVertex>> vertices = new HashMap<Integer, ArrayList<WorldVertex>>();
private static HashMap<Integer, ArrayList<Integer>> indices = new HashMap<Integer, ArrayList<Integer>>();

...

public static void processSegment(Segment segment) {
    BlockType[] mask = new BlockType[4096];
    boolean[] done = new boolean[4096];

    Block block;
    BlockType type;
    int x, y, z;
    int y_, z_;
    int k;
    int w = 0, h = 0;
    int sum;
    int i, j;
    int q, p;
    boolean done_;
    boolean continue_;

    int bX, bY, bZ;
    int segX = segment.getAbsPos().x * 16;
    int segY = segment.getAbsPos().y * 16;
    int segZ = segment.getAbsPos().z * 16;

    // Filling the mask with the blocktypes, every block which is not visible (or isn't there) will be masked with AIR
    for (i = 0; i < 4096; i++) {
        block = segment.getBlock(i);
        if (block == null) mask[i] = BlockType.AIR;
        else if (!block.isVisible()) mask[i] = BlockType.AIR;
        else {
            mask[i] = block.getType();
        }
    }

    // Loop through the six sides 0TOP 1BOT 2LEFT 3RIGH 4FRONT 5BACK
    for (i = 0; i < 6; i++) {
        // Faces of the segment which are not facing the camera should not be rendered
        if (!shouldRenderSegSide(i, segX, segY, segZ)) continue;

        continue_ = true;
        for (j = 0; j < 4096; j++) {
            if (mask[j] == BlockType.AIR) {
                done[j] = true;
                continue;
            }

            // All the blocks of which the current face is not visible should not be rendered
            block = segment.getBlock(j);
            if (!block.isSideVisible(i)) done[j] = true;
            else {
                done[j] = false;
                continue_ = false;
            }
        }
        if (continue_) continue; // Skips the rest of the code for this side if the side somehow appears to be empty

        for (y = 0; y <  16; y++) { // Loops through all the blocks (of the segment)
            y_ = y << 8; // This is for calculating the index of a 1-dimensional array
            bY = y + segY; // Absolute Y-value of the block in the world
            for (z = 0; z < 16; z++) {
                z_ = z << 4;
                bZ = z + segZ;
                for (x = 0; x < 16; x++) {
                    sum = x + z_ + y_;
                    if (done[sum]) continue;
                    bX = x + segX;
                    type = mask[sum];

                    // Finding with and height
                    done_ = false;
                    if (i == Side.TOP || i == Side.BOT) {
                        for (w = 0; mask[sum + w] == type && !done[sum + w] && w < 15 - x; w++) {} // x

                        for (h = 0; h < 15 - z; h++) { // z
                            q = sum + (h << 4);
                            for (k = 0; k <= w; k++) { // x
                                if (mask[q + k] != type) {
                                    done_ = true;
                                    break;
                                }
                            }
                            if (done_) break;
                        }

                        // Make sure the block won't be used again
                        for (j = 0; j <= h; j++) { // z
                            q = j << 4;
                            for (k = 0; k <= w; k++) { // x
                                done[sum + q + k] = true;
                            }
                        }
                    } else if (i == Side.LEFT || i == Side.RIGHT) {
                        for (w = 0; mask[sum + (w << 4)] == type && !done[sum + (w << 4)] && w < 15 - z; w++) {} // z

                        for (h = 0; h < 15 - y; h++) { // y
                            q = sum + (h << 8);
                            for (k = 0; k <= w; k++) { // z
                                if (mask[q + (k << 4)] != type) {
                                    done_ = true;
                                    break;
                                }
                            }
                            if (done_) break;
                        }

                        for (j = 0; j <= h; j++) { // y
                            q = sum + (j << 8);
                            for (k = 0; k <= w; k++) { // z
                                done[q + (k << 4)] = true;
                            }
                        }
                    } else if (i == Side.FRONT || i == Side.BACK) {
                        continue; // TEMP
                    }

                    addVertices(type.getColor(), i, bX, bY, bZ, w, h);
                }
            }
        }

    }
}

private static void addVertices(Vector3f color, int side, int x, int y, int z, int w, int h) {
    ArrayList<WorldVertex> sideVertices = vertices.get(side);
    ArrayList<Integer> sideIndices = indices.get(side);

    if (side == Side.TOP) {
        sideVertices.add(new WorldVertex(new Vector3f(x - 0.5f,     y + 0.5f,   z - 0.5f),      color));
        sideVertices.add(new WorldVertex(new Vector3f(x - 0.5f,     y + 0.5f,   z + 0.5f + h),  color));
        sideVertices.add(new WorldVertex(new Vector3f(x + 0.5f + w, y + 0.5f,   z + 0.5f + h),  color));
        sideVertices.add(new WorldVertex(new Vector3f(x + 0.5f + w, y + 0.5f,   z - 0.5f),      color));
    }

    if (side == Side.BOT) {
        sideVertices.add(new WorldVertex(new Vector3f(x - 0.5f,     y - 0.5f,   z - 0.5f),      color));
        sideVertices.add(new WorldVertex(new Vector3f(x + 0.5f + w, y - 0.5f,   z - 0.5f),      color));
        sideVertices.add(new WorldVertex(new Vector3f(x + 0.5f + w, y - 0.5f,   z + 0.5f + h),  color));
        sideVertices.add(new WorldVertex(new Vector3f(x - 0.5f,     y - 0.5f,   z + 0.5f + h),  color));
    }

    if (side == Side.LEFT) {
        sideVertices.add(new WorldVertex(new Vector3f(x - 0.5f,     y + 0.5f + h,   z + 0.5f + w),  color));
        sideVertices.add(new WorldVertex(new Vector3f(x - 0.5f,     y + 0.5f + h,   z - 0.5f),  color));
        sideVertices.add(new WorldVertex(new Vector3f(x - 0.5f,     y - 0.5f,   z - 0.5f),      color));
        sideVertices.add(new WorldVertex(new Vector3f(x - 0.5f,     y - 0.5f,   z + 0.5f + w),      color));
    }

    ... // For the other 3 sides

    // Adding indices for the 2 triangles
    sideIndices.add(sideVertices.size() - 4);
    sideIndices.add(sideVertices.size() - 3);
    sideIndices.add(sideVertices.size() - 2);
    sideIndices.add(sideVertices.size() - 2);
    sideIndices.add(sideVertices.size() - 1);
    sideIndices.add(sideVertices.size() - 4);
}

```

Can you help me to find what I did wrong? I've already looked multiple times at my code for a few hours, but I still cant find it.

EDIT: Got the idea for this meshing technique from this article

# Answer
> 0 votes
I've found what I've done wrong:

```
for (w = 0; mask[sum + w] == type && !done[sum + w] && w < 15 - x; w++) {}

```

The code above was wrong, because it incremented `w` first and then it checked everything. Therefor the code should be:

```
for (w = 0; w < 15 - x && mask[sum + 1 + w] == type && !done[sum + 1 + w]; w++) {}

```

This code is better, because:

1. It doesn't give an `ArrayIndexOutOfBoundsException` because I check if `w` is too large first.
2. It doesn't check the block which was already included (the first one at `w = 0`).
3. It does work.

And I applied a similar fix to the other loop which had to find the correct height.

Thanks for taking the time to look at my problem.

---
Tags: opengl, java, voxels
---


title: How to create 2D shadows and lighting?

text:
# Question
Title: How to create 2D shadows and lighting?
How do I create shadows and lights in a 2D top down perspective game? I want to achieve an effect similar to this game (also made in unity) where some objects like a torch, different sprites, and the player have a light source while the rest of the map is dark.

Do you anyone know how to achieve this, and could link me to some good resources on how to implement it in unity?

# Answer
For simple shadows you can create a material and select the shader as Sprite\>Diffuse , this will enable shadows on the sprite.

If you are looking for more than just shadows i.e. adding normal maps and other cool stuff, then check these two links give below :)

Writing a SpriteLamp Shader in Unity

Kencho's dev blog
> 4 votes

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


title: Smooth Wall Collision Detection

text:
# Question
Title: Smooth Wall Collision Detection
I've been working on a small game, and I've been stuck on the collision part. During the collision, when my player hits a block, he stops just as it should, but it then doesn't allow me to another direction (ex: the collision happens on the y axis, it won't allow me to move along the x axis). What I want is to be able to move along the wall while still moving into it (If you know what I mean). I've checked here and here, but they aren't what I'm looking for.

**EDIT:** The new code allows me to move along the axis's fine, but I'm getting some different problems (shown in pictures)

This is the **NEW** code for my collision detection:

```
if(key[KEY_A])
{
    if(tileMap[(x/zoomLevel)-1][y/zoomLevel] < 1 && tileMap[(x/zoomLevel)-1][(y/zoomLevel)+1] < 1)
    {
        if(tileMap[((x/zoomLevel)+1)][y/zoomLevel] < 1 && tileMap[((x/zoomLevel)+1)][(y/zoomLevel)+1] < 1)
        {
            x-=moveSpeed;
            dirX = 0;
        }
    }
}
else if(key[KEY_D])
{
    if(tileMap[(x/zoomLevel)+1][y/zoomLevel] < 1 && tileMap[(x/zoomLevel)+1][(y/zoomLevel)+1] < 1)
    {
        x+=moveSpeed;
        dirX = 1;
    }
}

if(jumping == false)
{
    if(tileMap[(x/zoomLevel)][(y/zoomLevel)+2] < 1)
    {
        y+=gravSpeed;
        gravSpeed*1.2;
        dirY = 1;
    }
}
else
{
    if(tileMap[(x/zoomLevel)][(y/zoomLevel)-1] < 1)
    {
        gravSpeed = 4;
        y-=gravSpeed;
        dirY = 0;
    }
}

```

Thanks to anyone who can help me with my problem!

**And here are some picture based on the new collision:**

Falling on ground:

Moving to the left when on top of a block:

Moving to the left:

Jumping when moving right:

# Answer
I've been implementing some very similar collide-and-slide collision detection and resolution. http://metareal.net/blog/wp-content/uploads/2015/08/2015-08-21.jpg

The main key I found was to handle X and Y separately. So, your code might be modified something like this (a little freeform but you should get the idea):

```
// step 1, modify X
prevX = x;
x += movementX;
work out top, left, bottom, right
if(new span collides with anything) x = prevX;

// step 2, modify Y
prevY = y;
y += movementY;
work out top, left, bottom, right
if(new span collides with anything) y = prevY;

```

In certain cases, the order of checking x and y will make a difference. Specifically, heading directly onto a colliding corner will now favor X movement. This is probably ok, but can be changed if you need. (Literally a corner case!)

Hope that helps a little.
> 2 votes

---
Tags: c++, collision-detection, tilemap
---


# Question
Title: How to set up the camera for a PS Vita game?
I am starting my first project for Unity and I want to start a new game for **PS Vita**. This console has a resolution of 960x544 pixels.

How do I have to set up my camera so that it adapts to this aspect ratio?

# Answer
The Unity Camera will always fit to the height , and it will scale its width towards left and right. You don't need to do anything to the camera to adapt it to 960x544. For testing purpose you can add a custom screen size to see how the actual game will look like. Go to Game window and select the drop down beneath to add a custom screen size.

Reference Image:-
> 0 votes

---
Tags: unity, camera
---


title: Multithreaded Game Loop

text:
# Question
Title: Multithreaded Game Loop
I'm trying to implement a multithreaded game loop. I already did that but had to use a few locks for that, which ruined the performance. After researching a bit I came up with this idea:

Instead of splitting the engines subsystems into different threads (e.g. physics, animation), all subsystems run on all threads. So when we got four CPUs, four threads are created, with each thread having one loop for all subsystems. So the single-core game loop is copied on all four threads. These game loops are controlled by one other loop, which sends messages (or 'jobs', 'tasks') to one of these threads (depending on their usage) according to user-input or scripts. This could be done with a double buffered command buffer.

Only the rendering loop is alone in a thread for maximum rendering performance. Now I'm thinking of the best way to communicate with the rendering loop. The best idea I could come up with is to again use a command buffer and swap it when the rendering loop is complete. That way the rendering loop doesn't have to wait for any of the loops and can go on rendering. If the game loop hasn't finished when the rendering loop swapped the buffer, all commands after that will be executed in the next frame of the rendering loop. To make sure that all objects will be drawn even if the game loop hasn't finished, the rendering loop holds all objects that will be drawn and draws them until it gets the command to stop drawing them.

My goal is to make the engine scalable to cpu numbers and make it to use all cores. Is this a way to do that? What is the best approach to this and how are modern engines handling this?

# Answer
Best practices:

* One central loop in main / rendering thread which also handles sound, network buffering etc. - basically, this centralises communication with OS and other threads.
* All processor-intensive tasks (for example, mesh building, AI, physics) may be submitted ad-hoc, in bite-sized work units, to existing worker threads. These threads are kept alive and re-used over and over for different tasks. A typical implementation pattern is *Thread Pooling*.

You can see examples of this in modern platforms like Unity (WorkerThread), Xamarin (ThreadPool), and HTML5 (WebWorker), and even in older tech like Java 6 (various approaches).

If you find you are waiting around a lot on mutexes, you probably need to restructure things. Try to parallelise your tasks such that only one thread accesses a given piece of memory at a given time. For example, if one worker thread is continuously working on bite-sized dynamic lighting tasks, while another is working on AI, then you cannot have a conflict of interests. Alternatively, have 2 worker threads on AI, but let them consume work units that don't affect one another's results.

And yes, rendering should be continuous, regardless. In the main loop, prior to render, *copy* results of any completed worker thread tasks into your main data model if they are complete (**see below**). But don't try to read the same model data from the renderer, that you are currently reading/writing in worker threads. That's obviously a recipe for disaster.

I strongly discourage the use of multiple loops which you will need to periodically synchronise - in fact it just sounds like a recipe for pain.

**Knowing when a work unit is complete & synchronising with main loop**

The exact mechanism for notifiying when a job on another thread has completed depends on your configuration: platform, language, threading environment. Even within C++ there are various threading environments like pthreads, OpenMP threading, etc. You will either be notified by some sort of callback, or you will have to poll some condition from the main loop regularly to check if each work unit is complete. Search for the mechanism that is used in your threading environment. I suggest finding and running some simple examples first, to thoroughly grok threading concepts. If you want to go standard, go pthreads, but understand that it is a very low-level threading library. P.S. If you are using pthreads, the book *Multi-Threaded Game Engine Design, 1st Edition*, handles this on page 84 onward... you should be able to find the preview on google books.
> 8 votes

---
Tags: opengl, c++, rendering, multithreading
---


title: traversing the area

text:
# Question
Title: traversing the area
i want to move point along spiral like hexagon for example i want to traverse the whole area and my player (point) is standing where i have placed it manually. now i want to start from this point and move outwards in concentric hexagonal path so that it moves along a bigger hexagon each time till it has covered the entire area. kindly suggest me how to develop such algorithm in c++ or simple c.

# Answer
> 0 votes
Lets say player is at origin, and you have (any convex shape should work) your inner-most hexagon defined as array `vec2 shape[6]`. The simplest algorithm would be:

```
int windingsNo; //=some value
const int vertexCount = 6;
vec2 shape[vertexCount];
float scale = 1.f;
for(int w = 0; w < windingsNo; w++)
{
  for(int v = 0; v < vertexCount; v++)
  {
    scale *= 1.1; // or += .1f
    player.MoveTo(shape[v] * scale);
  }
   //if you wish non-spiral path like on image, move scaling here, requires one more move().
}

```

or in other words: 1) move onto inner-most shape 2) move on vertex with index +1 on +1 bigger shape. This has the upside you can make gradually bigger absolute size difference if you put relative scaling (e.g. `scale *= 1.1`) in the inner loop. Translating the path to the desired location is now trivial.

---
Tags: c++, algorithm, c
---


# Question
Title: SDL.NET no longer detecting modifier keys
I'm using SDL.NET with C#. Recently, a bug has appeared where the library does not detect if the shift key is held down; although it used to do so.

```
private static void KeyboardEventHandler(object sender, KeyboardEventArgs args)
    {
            case (Key.Comma):

                if (args.Mod == ModifierKeys.LeftShift || args.Mod == ModifierKeys.RightShift || args.Mod == ModifierKeys.ShiftKeys) { actionBuffer = GameAction.MoveU; Console.WriteLine("Going up..."); }
                else { actionBuffer = GameAction.Pickup; }
                break;

            case (Key.Period):
                if (args.Mod == ModifierKeys.LeftShift || args.Mod == ModifierKeys.RightShift || args.Mod == ModifierKeys.ShiftKeys) { actionBuffer = GameAction.MoveD; Console.WriteLine("Going down..."); }
                else { actionBuffer = GameAction.Wait; }
                break;

            default:
                actionBuffer = GameAction.Null;
                break;
        }
    }

```

However, recently, the checks to see if a shift key is held have returned incorrectly false, despite previously previously evaluating to true.

This means the function never returns the "MoveU" or "MoveD" values, just the "Pickup" and "Wait" values. Why is this? Thanks in advance.

# Answer
The modifier keys can be combined with OR-bits. You need to use AND-bits to test for the modifier flags since it could contain all of CTRL+ALT+SHIFT (Left AND Right) and even some other modifier keys.

For example, if NumLock or CapsLock is ON, the value will never be == to LeftShift.

See the documentation for the ModifierKeys.

It is also not necessary to test for LeftShift, RightShift and ShiftKeys all at the same time. Just ShiftKeys is sufficient if you are treating them both the same.

`ModifierKeys.ShiftKeys == (ModifierKeys.LeftShift | ModifierKeys.RightShift)`

Try:

```
private static void KeyboardEventHandler(object sender, KeyboardEventArgs args)
{
        case (Key.Comma):

            if ((args.Mod & ModifierKeys.ShiftKeys) != 0) { actionBuffer = GameAction.MoveU; Console.WriteLine("Going up..."); }
            else { actionBuffer = GameAction.Pickup; }
            break;

        case (Key.Period):
            if ((args.Mod & ModifierKeys.ShiftKeys) != 0) { actionBuffer = GameAction.MoveD; Console.WriteLine("Going down..."); }
            else { actionBuffer = GameAction.Wait; }
            break;

        default:
            actionBuffer = GameAction.Null;
            break;
    }
}

```
> 0 votes

---
Tags: c#, sdl, input
---


# Question
Title: XNA renderTarget, how to convert mouse coordinates to world position when upscaling
I'm currently developing a monogame game with a tile engine.

I have been experimenting with different tiles and sprites sizes : 16px, 32px, 64px I have settled for 32x32 pixels tiles rendered at a 64x64px size on screen.

I have read that a good way to do so is to use a **RenderTarget2D**. I've done so. It works well. I'm using **SamplerState.PointClamp** to keep the pixel aspect clean.

So for a 1440x900 resolution I use

```
 renderTarget = new RenderTarget2D(graphics.GraphicsDevice, 720, 450);

```

**My question** : when using the RenderTarget2D to upscale the screen, it logically messes up the camera I had working, and even more so the conversion of mouse coordinates to world coordinates. **How should I modify the camera and the "mouse coordinates" to world position function**. Is it even possible to convert properly mouse coordinates when you are upscaling everything with a renderTarget ?

Screenshot

This answer hints that it may be problematic, can somebody explain to me why ?

From the link : *so if your graphics aren't dependant on other graphical features like a mouse, then I would use a RenderTarget*

I can't find any resources about this. I always find a solution by myself, but this one is too much for me. Linear algebra is not my strong suit. Thank to anybody who can help.

My transform Matrix and Worldposition conversion

```
public Matrix Transform(GraphicsDevice graphicsDevice)
{
    m_Transform =

      Matrix.CreateTranslation(new Vector3(-m_CameraPosition.X, -m_CameraPosition.Y, 0)) *
         Matrix.CreateRotationZ(Rotation) *
         Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) *
         Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));

    return m_Transform;
}

public Vector2 Worldposition(GraphicsDevice graphicsDevice, Vector2 position)
{
    //Invert camera
    Matrix m_InvertTransform =
    Matrix.CreateTranslation(new Vector3(-(m_CameraPosition.X + ViewportWidth * 0.5f), 0, -(m_CameraPosition.Y + ViewportHeight * 0.5f))) *
    Matrix.CreateRotationZ(Rotation) *
    Matrix.CreateScale(new Vector3(Zoom, Zoom, Zoom)) *
    Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, 0, ViewportHeight * 0.5f));
    m_InvertTransform = Matrix.Invert(m_InvertTransform);
    //Transform the position
    Vector3 newPos3 = Vector3.Transform(new Vector3(position.X, 0, position.Y), m_InvertTransform);
    return new Vector2((newPos3.X - 720) , (newPos3.Z - 450) );
}

```

Edit :

In my Update() method :

```
Vector2 vector = new Vector2((int)player.X, (int)player.Y);
camera.ChangePosition(GraphicsDevice, vector);

```

The ChangePosition function in my Camera Class public void ChangePosition(GraphicsDevice graphicsDevice, Vector2 newposition) { m\_CameraPosition = newposition; }

# Answer
> 0 votes
So just to answer my own old question. I had already done what I was asking for in my prototype, and found my solution when looking back in my git repository. Only thing missing from the previous code was the division by 2 of the position in the transform Vector.

```
public Vector2 Worldposition(Vector2 position)
{

  float ViewportWidth = 720;
  float ViewportHeight = 450;

  //Invert camera
  Matrix m_InvertTransform =
  Matrix.CreateTranslation(new Vector3(-(m_CameraPosition.X + ViewportWidth * 0.5f), 0, -(m_CameraPosition.Y + ViewportHeight * 0.5f))) *
  Matrix.CreateRotationZ(Rotation) *
  Matrix.CreateScale(new Vector3(Zoom, Zoom, Zoom)) *
  Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, 0, ViewportHeight * 0.5f));
  m_InvertTransform = Matrix.Invert(m_InvertTransform);
  //Transform the position
  Vector3 newPos3 = Vector3.Transform(new Vector3(position.X / 2, 0, position.Y  2), m_InvertTransform);
>  return new Vector2(newPos3.X - ViewportWidth / 2, newPos3.Z - ViewportHeight  2);
}

```

---
Tags: xna, monogame, scale, rendertargets, tiles
---


# Question
Title: How can I make a gameObject jump quick at first then start slowing down after a while?
How can I make a gameObject jump quick at first then start slowing down after a while? It definitely has something to do with deltaTime.

# Answer
> 1 votes
You could disable the gravity on the Rigidbody and then just make gravity yourself by writing a script and using `GetComponent<Rigidbody>().AddForce(-Vector3.up * Time.deltaTime * YOUR GRAVITY VALUE)` and just change YOUR GRAVITY VALUE when ever you want the object to be slowed down.

# Answer
> 0 votes
Just to clarify, applying gravity to a specific rigidbody will not effect everything in the scene. If it does, then you have a larger issue about to come. Calling a reference to the rigidbody attactched to an object and adding gravity * Time.deltaTime will increase gravity until the player touches back down. At that point I would decide a max gravity value to be applied so when it's hit, it will not cause the object to come crashing down. Instead start reducing gravity until it touches down then reset gravity back to its starting value.

Edit: I'd suggest the possibility of using a switch and assigning transforms to bools as to set specific increments to gravity so on the way down it recheck the transforms again and reduce gravity.

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


# Question
Title: Monogame / XNA - Is there a limit when drawing at far position (> 1 billion ? = strange behavior)
So I'm making an "unlimited" 2D Tile-Engine with procedural generation (simple noise based) in Monogame, and I'm loading/unloading Chunck by Chunck as you go along. It's working pretty well now.

Only problem I encounter when I'm positioning my character at a high value like for example int.Maxvalue / 2 (and higher), drawing tiles and every sprites from a high Position becomes all glitchy. Tiles take random sizes with a higher width and height (see pictures).

**Drawing tiles :**

```
 spriteBatch.Draw(
   textToDraw,
   new Vector2(i * TILE_SIZE, j * TILE_SIZE),
   new Rectangle(0, 0, TILE_SIZE, TILE_SIZE),
   drawColor,
   0,
   new Vector2(0, 0),
   1f,
   SpriteEffects.None,
   depth
 );

```

**Camera Transform :**

```
public Matrix Transform(GraphicsDevice graphicsDevice)
{
   m_Transform =
     Matrix.CreateTranslation(new Vector3(-m_CameraPosition.X, -m_CameraPosition.Y, 0.0f)) *
     Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Width * 0.5f , graphicsDevice.Viewport.Height * 0.5f , 0.0f)); // on redivise par 0.5 à cause du renderTarget 720x450

   return m_Transform;
}

```

**Begin spriteBatch :**

```
matrix = this.Manager.camera.Transform(this.GraphicsDevice);
spriteBatch.Begin(SpriteSortMode.BackToFront,
    BlendState.AlphaBlend,
    SamplerState.PointClamp,
    null,
    null,
    null,
    matrix
);

```

**Drawing at position x = 1 million, y = 1 million :** **Drawing at position x = 1 billion, y = 1 billion:** Red tile is a random tile I draw in another color to be able to get the size. But all the tiles are glitchy.

To isolate the problem as it didn't seem to come from my code, I tested in an Internet XNA sample I modified (From xnagpa.net "Eyes of the Dragons" samples) working with a similar Camera and tile engine. I forced the Camera position to a high value (x = 1 billion, y, 1 billion) and drawing Tiles on the screen at that position. Same problem. So my newb guess is it has to do with calculation of the Matrix, but after that it gets too complicated for me.

Anyone had the problem ? Can confirm it is a limitation of some sort. I don't think it can be fixed, but I'm trying to determine what is the "limit" of my "unlimited world".

*Code is from my code base, pictures are from the example I cited and modified*

# Answer
This is a floating point issue and yes, you will get artifacts at very large values. The reason is because as the size of the value to the left of the decimal in a floating point number increases, you lose precision on the right side (and vice versa).

The fix is to change your point of origin so that your offset positions are always within an acceptable range. I had to do this for a space simulator.

EG. With my space simulator I used multiple points of origin depending on the proximity of the objects. Either using a planet, the sun or center of the galaxy as the origin with different scales for related objects. This allowed me to work in centimeters, kilometers and lightyears respectively.

Another possibility to help alleviate the problem without having to move your origin, is to use doubles instead of floats but you will eventually still run into the same problem but at a much greater distance.

One more option is to used fixed-point numbers or a big-number library but you will still need to do the matrix and vector math with floats/doubles, so it can get a bit complicated that way.
> 1 votes

---
Tags: xna, monogame
---


title: Why isn't my cbuffer updating?

text:
# Question
Title: Why isn't my cbuffer updating?
I am really frustrated because my cbufer isn't updating. This is my VS:

```
cbuffer MatrixBuffer: register(b0)
{
float4x4 worldViewProj;

};

struct VertexIn
{
float4 Pos : POSITION;
float4 Color: COLOR;
};

struct PixelIn
{
float4 PosH : SV_POSITION;
float4 Color: COLOR;
};

PixelIn VS (VertexIn vin)
{
PixelIn vout;

vin.Pos.w = 1.0f;

vout.PosH = mul(vin.Pos, worldViewProj);

vout.Color = vin.Color;

return vout;
}

PixelIn VS1(VertexIn vin)
{
PixelIn vout;

vin.Pos.w = 1.0f;
vout.PosH = vin.Pos;

vout.Color = vin.Color;

return vout;
}

```

When using VS1 it draws correctly, but when using VS it doesn't draw anything?

Here is my CBUFFER update code

```
bool Game::UpdateShaders()
{
    HRESULT result;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    MatrixBufferType* dataPtr;

    worldViewProjM = worldM * viewM * projM;
    worldViewProjM = XMMatrixTranspose(worldViewProjM);
    result = md3dDeviceContext->Map(mMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
    if (FAILED(result))
    {
        MessageBoxW(mMainWnd, L"FAOE:", 0, 0);
        return false;
    }

    dataPtr = (MatrixBufferType*)mappedResource.pData;

    dataPtr->worldViewProj = worldViewProjM;

    md3dDeviceContext->Unmap(mMatrixBuffer, 0);

    int NBuffers = 0;

    md3dDeviceContext->VSSetConstantBuffers(0, 1, &mMatrixBuffer);
    //md3dDeviceContext->PSSetConstantBuffers(0, 1, &mMatrixBuffer);

    return true;
}

```

Here is my MATRIXBUFFERTYPE struct:

```
struct MatrixBufferType
{
        XMMATRIX worldViewProj;
};

```

This is called after I clear my depth stencil view and render target view. Does somebody know why my CBUFFER isn't updating?

Thanks in advance.

# Answer
> 0 votes
you have to update your subresource (if i'm not mistaken):

```
md3dDeviceContext->UpdateSubresource(mMatrixBuffer, 0, NULL, &worldViewProjM, 0, 0);

```

# Answer
> -1 votes
Setting the cbuffer variable to matrix fixed it for me. Thanks all for youre help!

---
Tags: directx11, hlsl, c++
---


# Question
Title: How does one obtain an official Nintendo development SDK?
I've seen before a topic here asking if there is any significant differences between using PALib or Nintendo's Nitro SDK... and that got me curious: what does it take to obtain the official SDK ?

# Answer
Costs I can't speak on personally, and I don't know if anyone who is a licensed developer can either. But there are some requirements that I do know of. I don't imagine it is that expensive because from what I saw around the internet the development kit for the Wii is under 5k.

What will cost you however, is having a brick-and-motar location dedicated to your studio's work. Nintendo requires this of it's licensees.

Following that, they also request back financials so that they can ensure that you would actually have the resources to bring your game to market.

If you think you qualify, you can fill out the application to become a licensed Nintendo Developer.
> 15 votes

# Answer
$2,000 to $10,000 is the range given by Nintendo.

From Nintendo of America:

> Development Kits: Approximate development costs range from $2,000 to $10,000, depending on the size of your team. Financial stability is expected by Authorized Developers in order to purchase the necessary development equipment for your project.
> 2 votes

# Answer
I'd say in most cases it's handled by the publisher. Don't have a publisher/want to self publish? Nintendo probably doesn't want to talk to you, then. If you had some industry connections it might be a different story, of course.

It's a case of "if you have to ask, you'll never know".
> 1 votes

# Answer
A couple of years ago I developed on the DS, the DS-Lite kit costed 1800$ which was way cheaper than any other dev-kit at the moment.

The Wii was a bit more expensive (I don't remember, 2500? 3500?) but you need to have at least two types, one for development (the black box) and one for creating the masters (green I think but I'm not sure).

For what it is worth: Unofficially "everyone knew" that you had to request twice for being granted to be an authorised Nintendo developer...
> 0 votes

# Answer
because of our NDA we can not talk about this much but it might be a good idea to apply for a license yourself it takes a few months to get a license (it took me 4 months), but then you can any question you want to the people of nintendo, but use the email that is registered with nintendo for that what i can say is that nintendo uses HTML 5 and javascript development for its native SDK but has support for unity to but for any further info please contact nintendo of america
> -3 votes

---
Tags: nintendo
---