# Question
Title: Reuse VertexBuffer or new VertexBuffer object?
I'm trying to render bitmap fonts in directX10 at the moment, and I want to do this as efficiently as possible. I'm having a hard time getting a start on my design because of this question though.

So should I reuse a single VertexBuffer or make multiple VertexBuffer objects?

Currently I allocate one dynamic VertexBuffer per Quad object in my program. This way I wouldn't have to map/unmap a VertexBuffer if nothing moves on my screen. For fonts I can implement a similar method on where I allocate one buffer per text box, or something similar.

After searching I read about reusing a single VertexBuffer for all objects. Vertex caching came up also. What is the advantage/disadvantage of this, and is it faster than my previous method?

For last, is there any other method I should look into rendering many 2d quads in the screen?

Thank you in advance.

# Answer
You may reuse VertexBuffer objects but this is harder to implement, but as @SeanMiddleditch said in his comment, this shouldn't be your goal, and creating new VBOs shouldn't matter in your application.

> Currently I allocate one dynamic VertexBuffer per Quad object in my program

Per quad is an overkill and is probably the worst. This way your practically emulating immediate mode which has been deprecated for good.

Also storing all your scene in one vertex buffer is usually a bad idea. You may need to cull objects and not draw them in the first place in many occasions. Storing them in one VBO will particularly prevent you from doing culling operations.

**Your best bet is to create new vertex buffers for each 3D model**, try not to store small data or huge data.

My recommendation is that it shouldn't be your concern unless your application really took a performance hit. In that case profile and optimize accordingly.

> After searching I read about reusing a single VertexBuffer for all objects. Vertex caching came up also. What is the advantage/disadvantage of this, and is it faster than my previous method?

Vertex caching is an *advanced optimization* and shouldn't be done unless you have a very performance critical application (like the next big AAA game, or a scientific visualization that deals with millions of data chunks), and btw vertex caching shouldn't matter for smaller scenes.
> 1 votes

---
Tags: directx, directx10, fonts, vertex-buffer
---


# Question
Title: Linear filter problem with diagonal lines on adjecent tiles
I am quite new at using OpenGL/GLSL. Basically, the project I am working on is my first 'real' experience with it. I do not know whether this is relevant, but I use for my project.

Currently, I am trying to use the `GL_LINEAR` filters to draw tile of my (tile) map (before I was using `GL_NEAREST` without problems).

My map contains diagonal roads (just simple lines in this example). A partial overview/example of my map (using the nearest filter without corrections):

With the `GL_NEAREST` filter, initially I added a 1 pixel border, so the tiles were slightly overlapping and the diagonal roads were draw without the small gaps at the edges of the tiles.

This does not work with the `GL_LINEAR` filter, because I suppose that the overlapping parts are drawn twice, resulting in a darker 'blob':

I tried to get rid of the blobs, by making the horizontal lines shorter, but there is always an irregularity, either a blob or an 'decrease of line width' (as seen in the diagonal part of the line).

So I removed the 1 pixel additional border and have this as a result:

Now I am trying to fill in the 'gaps' by drawing the two triangular fillers like this:

but I can't get it completely right (this is the best I managed to get):

I suppose it is virtually impossible to get this perfectly right by 'manually' drawing these triangles. Also, when looking at the third image, the lines at the 'edges' (that need to be filled) are very sharp. I suppose this is problematic..?

So, my question is: how does one solve this problem? Do I need to prepare/modify my textures for this? Can I use a shader to fill the gaps automatically? Is manually filling the gaps with the triangles the way to go? Or is there some entirely different technique to have smooth diagonal lines that span multiple tiles?

# Answer
> 2 votes
Unfortunately, the problem is hopeless as it stands. You cannot get acceptable filtering at boundaries without each tile being somehow more aware of its neighbours. I recommend changing the way you draw tiles.

Here is what you should do. First, render your tiles to an offscreen framebuffer at ratio 1:1 (using `GL_NEAREST`, which already works for you). Then, render the resulting texture to screen at the desired scale ratio (using `GL_LINEAR` for proper filtering).

---
Tags: opengl, glsl, tilemap, alpha-blending
---


# Question
Title: Where does the Game class come from in the DrawableGameComponent constructor?
I'm making a project to Windows Phone using Silverlight + XNA, but I don't know how I can use the `DrawableGameComponent` because the constructor requires a `Game` class, it looks like this:

Planet.cs

```
class Planet : DrawableGameComponent
{
    public Planet(Game game): base(game){

    {
}

```

but in my first page of Silverlight and XNA project not is a `Game` class it's this:

GamePage.xaml.cs

```
public partial class GamePage : PhoneApplicationPage
{
   ...
}

```

Where do I find the `Game` class to pass into the `DrawableGameComponent` constructor?

# Answer
> 1 votes
XNA + Silverlight projects no longer use the Game class nor do they use the DrawableGameComponent class.

A good article for migrating to XNA + Silverlight: http://xbox.create.msdn.com/en-US/education/catalog/article/migration\_guide\_moving\_to\_silverlight\_xna

# Answer
> 0 votes
The `DrawableGameComponent` should be instanciated inside a `Game` class.

```
DrawableGameComponent dgc = new DrawableGameComponent(this);

```

As an alternative you could extend the `DrawableGameComponent` with a new one defining your own constructor, but it would lack of sense

---
Tags: xna, xna-4.0, silverlight
---


# Question
Title: check if there are planets in the vicinity
I'm trying to make a random galaxy map in gamemaker, with several planets at random places. The problem I have run into is that some planets will be too close together. I need a way to put a minimum distance between them, but I can't figure out how to do it, or where I'm going wrong in the code.

I use the following script to make the map (argument0=amount of planets of this type to create and argument1=the object under which this type is located):

```
var i;
var MinDistance
var ToCloseFlag
var planetx, planety

for (i=0;i!=argument0;i+=1)
{
do
{
    do
    {
        do{
        planetx=random(room_width);
        }
        until(planetx<room_width-64 && planetx>64);
        do {
        planety=random(room_height);
        }
        until(planety<room_height-64 && planety>64);
    }
    until(place_empty(planetx,planety))
    MinDistance=400;
    ToCloseFlag = 0;

    with(argument1){
        if (point_distance(planetx,planety,other.x,other.y)<MinDistance)
            {
                ToCloseFlag=1;
            }
    }
 }
 until (ToCloseFlag=0);

    if place_empty(planetx,planety)
    {
        instance_create(planetx,planety,argument1);
    }

```

}

Any help would be greatly appreciated.

# Answer
You need to use some spatial partitioning in order to check for distance before consider a random position "good". Binary space partitioning can be useful: you construct a tree structure that you query before adding a position to get the closest one; if the closest is far enough you put the position into the tree so it will checked against the next position. If the current position is not far enough you reject it.

Take into the account that as you insert positions, the probability to reject the next position increases...

A differen aproach is to "cheat" by partition space before computing position. You can create a dense grid where each position is far enough from its neighbor, then you place randomly your planets in this grid. If the number of grid is large compared to the planets, you wont see the trick.

You can add some randomness to your grid by putting extra space between contiguous cells:

Let say you want L to be your minimal distance, then you can put your grid cells apart by L+2\*e; When you choose a cell, you can set the position of the planet to the center of the cell adding some random noise (at most e). In the worst case of two consecutige cells chosen and maximum random displace applied one toward the other, you will get L as distance.

In the above picture you can see how wider grids allow for random position within an area that assure you the required minimum distance even if position are placed the nearest possibile.

The tradeoff of this aproach is that adding randomness (e) you loose available cells and vice versa.
> 2 votes

---
Tags: game-maker
---


title: Planet sized quadtree terrain precision

text:
# Question
Title: Planet sized quadtree terrain precision
I've been working on a planet sized and shaped terrain lib for a while (In webgl and Unity) and have a couple of working implementations \[Quadtree cubesphere and circular clipmaps\].

But both of them suffer from the same problem. In the GPU vertex shader I move the vertices to their correct location on the planet. But 16 bit floats can't handle values that go into the millions. So when you get close to any vertex in the terrain it jiggles from the GPU rounding errors.

With the quadtree solution this is how I put vertices where they belong in the shader:

```
vec3 newPosition = vec3(normalize(StartPosition.xyz + (WidthDir * position.x + HeightDir * position.y) * Width) * Radius);

```

In the circular clipmaps I create a point at 0,0,1 and use two quaternions to rotate it to where it belongs (one for where the point is in the clipamp and one for where the clipmap should appear on the planet), then multiply it by the planet radius.

But both implementations require the multiplication of the planet's radius \[the clipmap also has one quaternion with precision far higher than a 16 bit float, at ground level it will be a precision of 1/6000000 of PI\].

So does anyone know how to handle this problem on the GPU so that at least the points closest to the camera have position values close to zero and no large number multiplication? Or is the only solution to set the positions on the CPU and just do some math work to make sure the vertices on the side of the planet closet to the camera always have values close to zero?

# Answer
> 5 votes
You can read a more detailed answer here:Which is the best LOD method for planet rendering?

I'm doing exactly something similar for my computer science degree thesis and attacked the same problem.

The problem you have is jitter, and you will find another one more called z-fighting.

Jitter: Most of today’s GPUs support only 32-bit floating-point values, which does not provide enough precision for manipulating large positions in planetary scale terrains. Jitter occurs when the viewer zooms in and rotates or moves, then the polygons start to bounce back and forth.

The best solution for this is to use "Rendering Relative to Eye Using the GPU" method. This method is described in the book "3D Engine Design for Virtual Globes" (I'm sure you can find it on the internet aswell) in where basically you have to set all your positions with doubles on CPU (patches, clipmaps, objects, frustrum, camera, etc) and then MV is centered around the viewer by setting its translation to (0, 0, 0)T and the doubles are encoded in a fixed-point representation using the fraction (mantissa) bits of two floats, low and high by some method (read about Using Ohlarik’s implementation and The DSFUN90 Fortran library).

Although the vertex shader requires only an additional two subtractions and one addition, GPU RTE doubles the amount of vertex buffer memory required for positions. This doesn’t necessarily double the memory requirements unless only positions are stored.

Depth Buffer Precision: Z-fighting. As we are rendering very large terrains, in this case: planets, the Z-buffer has to be HUGE, but it doesn't matter wich values you set for znear and zfar, there will always be problems.

As the Z-buffer depends on a float point interval, and also it is linear (although perspective projection is non linear) values near the eye suffer from Z-fighting because the lack of precision 32-bit floats have.

The best way to solve this problem is to use a "Logarithmic Depth Buffer" http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html

A logarithmic depth buffer improves depth buffer precision for distant objects by using a logarithmic distribution for zscreen. It trades precision for close objects for precision for distant objects. Since we are rendering with a LOD method, far objects require less precision because they have less triangles.

I hope I could help, if you need anything more you can email me.

---
Tags: graphics, terrain, quadtree
---


title: Android local multiplayer

text:
# Question
Title: Android local multiplayer
I am working on a FPS game for Android and I want to make a support for local multiplayer with no additional devices or server required. One of the player's devices would serve as a server, getting and distributing all the messages, OR every device broadcasts messages to everyone inside the group. First I was thinking bluetooth or wifi direct, but I am running into many problems with both. The plan was to support up to 10 players, so I am not sure bluetooth can handle that (broadcast messages and similar). If it is possible, let me know. Also, I heard of an option to make a wifi hotspot on one device, and connect all other devices to it that way, but I have no idea how that would work. Does anyone have any real experience with this, or any advice on how to implement it? Thanks in advance.

PS. yes, I've ran through everything on android developers site, but their wifi direct example is kinda bad and only supports 1-way data transfer.

# Answer
Wifi communication via sockets would be the way to go. You will need to implement the higher-level stuff yourself, such that you won't have network discovery out of the box.
> 0 votes

---
Tags: java, android, multiplayer, realtime, bluetooth
---


# Question
Title: How can I kill a libGDX AsyncTask immediately?
Is there any way of killing a running `AsyncTask` immediately in libGDX?

The `AsyncExecutor` that submits it seems to just have one method (`dispose()`) that kills all the `AsyncTask`s that it handles after they've all managed to complete their runs.

Currently, to achieve what I want, I use a volatile boolean in the task class, loop on its value in the `call()` method of the same class, and then set it to false whenever I want to interrupt that specific task immediately.

I wonder though whether there's another, more direct, way of achieving this. Is there any other class or method responsible for this?

# Answer
> 3 votes
There appears to be nothing built-in to the `AsyncTask` API for this (most similar APIs have cancellation support, but libgdx's doesn't appear to).

You can implement it yourself. A simple approach is to use an appropriate thread synchronization primitive to control or act as signal to your asynchronous task that it should terminate stop working and early-out.

Properly guarded or marked up, a simple Boolean can suffice. Typically this means you will need to either check if the Boolean has been set to signal cancellation at the top of your tasks main loop and/or periodically throughout the execution of your task.

You can wrap this behavior up in your own utility class to avoid having to repeat it for every async operation you want to build, but even if you remove that boilerplate work you'll still have the issue where the cancellation is not *immediate*, it only happens at the level of granularity you perform the cancellation check. This is actually bad (because it means you could have a long wait between requesting a cancel and the actual cancel happening) *and* good (because it means you can make sure it's not possible to abort the async task while it's in the middle of transitioning some data between two valid states, and that way you ensure class invariants remain in place).

---
Tags: java, libgdx
---


title: XNA 2D Camera, zoom into player

text:
# Question
Title: XNA 2D Camera, zoom into player
My 2D camera follows the character fine without any zooming. However, when I tried adding a zoom feature using the Matrix.CreateScale(), the camera no longer follows the character properly.

```
public class Camera
{
    private Matrix transform;

    public Matrix Transform
    {
        get { return transform; }
        set { value = transform; }
    }

    public Viewport view;
    public  Vector2 center;
    float zoom;
    float rotation;
    public float Zoom{
        get{return zoom;}
        set { value = zoom; }
    }

    public Camera(Viewport newView)
    {
        view = newView;
        zoom = 2;
        rotation = 0;
    }

    public void Update(Vector2 position, int xOffset, int yOffset)
    {

        if (position.X < view.Width / 2)
            center.X = view.Width / 2;
        else if (position.X > xOffset - (view.Width / 2))
            center.X = xOffset - (view.Width / 2);
        else center.X = position.X;

        if (position.Y < view.Height / 2)
            center.Y = view.Height / 2;
        else if (position.Y > yOffset - (view.Height / 2))
            center.Y = yOffset - (view.Height / 2);
        else center.Y = position.Y;

        transform = Matrix.CreateTranslation(
            new Vector3(-center.X + (view.Width / 2), -center.Y + (view.Height / 2), 0)) *
            Matrix.CreateScale(Zoom, Zoom, 1.0f) * Matrix.CreateRotationZ(rotation) *
            Matrix.CreateTranslation(-center.X + (view.Width / 2), -center.Y + (view.Height / 2), 0);

    }
}

```

The camera is updated with:

```
camera.Update(character.Position, map.Width, map.Height);

```

With the width and height of the tilemap and the characters current position. If I change the zoom factor how do i keep the player still in the center w/ the camera following?

# Answer
From just a quick glance it looks like your matrix is incorrect. ISROT (identity, scale, rotate, orbit, translation) is the order you should apply your operations. Your applying translation twice for some reason.

```
transform =
    Matrix.CreateScale(Zoom, Zoom, 1.0f)
    * Matrix.CreateRotationZ(rotation)
    * Matrix.CreateTranslation(-center.X + (view.Width / 2),
                               -center.Y + (view.Height / 2),
                               0);

```
> 2 votes

---
Tags: xna, c#, 2d, camera, matrix
---


title: How can I create a glitter effect?

text:
# Question
Title: How can I create a glitter effect?
I am trying to create a glittering effect for my realtime shader but I don't know how.

Here is one example, and another example.

What technique can I use to implement this?

# Answer
There's an interesting article AMD - Getting Procedural.

It seems that sparkles are harder than I think.
Decent solution: Use 3D position to index 3D noise function, add the view vector, use frac function to further randomize things.

```
Sparkle:
float specBase = saturate(dot(reflect(-normalize(viewVec), normal),
lightDir));
// Perturb a grid pattern with some noise and with the view-vector
// to let the glittering change with view.
float3 fp = frac(0.7 * pos + 9 * Noise3D( pos * 0.04).r + 0.1 * viewVec);
fp *= (1 - fp);
float glitter = saturate(1 - 7 * (fp.x + fp.y + fp.z));
float sparkle = glitter * pow(specBase, 1.5);

```
> 3 votes

# Answer
Well, when asked to design any shader, we should start by breaking things down to smaller problems. And just as note the glittering effect doesn't actually makes the shader looks good, but the overall lighting and effect, using only one of them won't look as good.

First of all let us state what is not directly part of the shader:

1. The shadowing is not part of the shader, and it is done via separate shadowing pass.
2. I **assume** there is ambient occlusion (especially that this image shown in the question is particularly not using real time renderer but that's an assumption).

Secondly, let's break the actual shader into separate effects:

1. There is an anisotropic like lighting, this is very essiental to the overall look of the shader. The reason behind this, is that the actual material contains fabrics, these shiny fabrics makes the light reflection have directional bias, making the most *amount* of reflected light in that certain direction.

Note that such fabrics have infinitely many normals, but the technique described here approximates the most significant normal

In order to approximate the most significant normal, one way to do, is to use texture coordinates and calculate tangents of the mesh, and instead of calculating **N**.**L** you calculate 1-(N.T).

Full explanation here. And you probably need to implement that in fragment shader rather than the vertex technique they talk about. Other anisotropic models can also apply.

Now for the glittering effect:

This can be done in world space/local texture space, or screen space as a separate pass.

The algorithm I can think off, uses image processing technique (assuming the mesh have texture coords).

* Generate a high frequency 2D noise on the mesh surface using it's texture coordinates, perlin noise seems a good candidate.
* Apply a max filter using 3x3 kernel on the noise. This will generate an effect similar to the below image, and the max filter is described here.

Note the above image is just an example of the max filter, and applying it on the noise will give sth similar to a star field.

* Once you have done this, apply a Gaussian filter with certain deviation on the noise to get star like shape.

Example of Gausian filter applied on max(ed) noise.

* The final step is to combine this with orginal mesh texture and light. This is best done using an (|) or-ing binary operation with the original mesh texture/color, this will take only the white from the noise and remove any black pixels. Regarding the light (and possibly other specular maps) the best thing to do is to add it or modulate it with your previously combined pixels. You may also need a glow post-processing effect for a better glow.

Note, this technique might need significant optimzation for a real time shader.
> 10 votes

---
Tags: opengl, directx, shaders, glsl, hlsl
---


title: How I can advertise my browser game

text:
# Question
Title: How I can advertise my browser game
I developed a browser-based game. It's a Multiplayer Business Strategy Game. Currently I am unable to find a place where I can advertise my game. My main requirements are :

1. I can only pay via Credit Card. No Paypal. Just tell me which ad company accepts credit cards.
2. I also have quite a limited budget.

Also, I want to know is their is any rating / review website for my type of game?

# Answer
> 2 votes
I would say that the best option is to use Facebook ads or Google ads. I have had pretty good success using FB for advertising because you can set a daily spending limit and you can target your (fairly close) audience. I would also suggest a facebook page for your game.

I personally am not a huge FB fan but I can vouch that doing that really helps.

# Answer
> 1 votes
Let me ask you: How do you intend to make money with your game?

If your game just have advertisement as the revenue source, I ***highly*** discourage you to invest even $0.01 in marketing. You will spend money foolishly. I know because I've been there.

Why? You will expend at least $0.10 / click. Suppose that 1,000 users click in ads you set to acquire users. You expended $100.

Now you must be aware that the eCPM of ads inside your game will pay you at most $25/1,000 clicks. But usually it's around $0.10/1,000 clicks.

If all acquired users clicked in the ads inside your game, you would get at most $25. A loss of $75.

But notice that the CTR (how many clicks per 100 users apps/games usually get) is around 2%.

So, you can expect that from 1,000 users you will get around 20 clicks. For the highest eCPM ($25/1,000 clicks) you would earn $0.50. A loss of $99.50.

Let me repeat once more: only invest money in marketing *if* your application has in-app purchase in it *and* you expect to earn much more than you will invest.

Note: for in-app purchase, it's expected that around 7% of active user base will expend money. All other users won't expend anything.

---
Tags: browser-based-games, marketing
---


# Question
Title: Physics engine deltaTime and force acceleration
I am working on a physics engine that uses basic Euler integration to compute forces. So, here is the thing:

```
function applyForce (rigidbody, force) {
    rigidbody.forces.add(force);
}

function computeAcceleration (rigidbody) {
    rigidbody.acceleration = rigidbody.forces / mass;
    rigidbody.velocity = rigidbody.velocity + rigidbody.acceleration * time.deltaTime;
}

// The forces are reset after each gameloop

```

So now imagine I want to apply a force to jump, I will use `applyForce` at the moment the player presses the jump button.

But: What happens is that the amount of movement depends on the gameloop speed, since the force is applied for a single frame. I feel like I missed something about how you should use forces, but I don't see how I should manage it properly.

In which cases should we use a force, considering this deltaTime issue? And also, what should I use instead?

# Answer
It’s because, in general, jumping involves applying an impulse instead of a force.

You apply forces when the interaction is expected to last for at least some time. For instance, gravity is a force: it lasts more or less forever. Pushing a door is applying a force, too: you keep pushing while the door opens.

You apply impulses when the interaction should be more or less immediate. Jumping, or hitting a ball with a bat: this involves impulses. Everything happens in a very short timespan.

This is how you could modify your code in order to apply impulses in addition to forces:

```
function applyForce (rigidbody, force) {
    rigidbody.forces.add(force); // This is still valid, but not for jumping
}

function applyImpulse (rigidbody, impulse) {
    rigidbody.impulse.add(impulse);
}

function computeAcceleration (rigidbody) {
    rigidbody.acceleration = rigidbody.forces / mass; // This is still valid
    rigidbody.velocity = rigidbody.velocity
                       + rigidbody.impulses / mass
                       + rigidbody.acceleration * time.deltaTime;
}

```

Of course, as suggested by MickLH, you should probably use Verlet integration instead of Euler (by averaging the previous velocity and the new velocity), too. But the main problem you have is forces *vs.* impulses.
> 4 votes

# Answer
The fix is simple, integrate position in the *middle* of integrating velocity. (As in, add half of the force, update, then add the other half.)

Here is a more in-depth explanation: http://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html
> 2 votes

---
Tags: physics, game-loop, timestep
---


# Question
Title: Are prefabs the only way to dynamically build a world in Unity?
I'm trying to understand how to setup my Unity prefabs and scripts to dynamically spawn a series of "encounters", with each encounter containing several `GameObject`s.

For example, imagine spawning the next several portions of an infinite-runner level. One encounter is a ramp, the other encounter is a pit with some coins.

This is what I am currently doing:

1. A global `SceneManager` script has a handle to an `EncounterFactory` prefab. When needed, the `SceneManager` will begin constructing the game world.
2. The `EncounterFactory` prefab contains a script that has a method `SpawnRandomEncounter`. The `EncounterFactory` also contains handles to several other prefabs for the objects that can be found in an encounter.
3. The `SpawnRandomEncounter` method uses the prefabs linked to `EncounterFactory` and builds the expected `GameObjects`.

So when building out a new "encounter", the `SceneManager` clones the `EncounterFactory` (which serves as the parent object for the full encounter), and then calls `SpawnRandomEncounter` to build out the child objects.

This seems suboptimal. First, I need to have myriad prefabs for each thing that *could* be spawned. It also requires a meta-prefab to `EncounterFactory`. That is, a prefab who just allows me to spawn other prefabs.

Is there a better way to dynamically build out a game world or level in Unity? Or is it prefabs upon prefabs upon prefabs?

For example, I'm aware that I can find an existing object by name. (e.g. find `EncounterTemplate5` and clone that.) However, that requires that `EncounterTemplate5` *exist* in the game world. (So it can be cloned.)

# Answer
> 3 votes
First off, do you know about having a Resources folder? Assets put in there can be loaded in code by name, instead of needing to reference them within the scene. Putting dynamically loaded assets in a folder called "Resources" makes dynamically loading assets a lot more flexible.

The assets that you load from Resources don't have to be prefabs, although you usually want them to be in order to already have their various components and whatnot already setup. However if making everything a prefab is onerous for some reason then you could load the obj mesh (or whatever) and then AddComponent

---
Tags: unity
---


# Question
Title: 2D lighting causes black rings to appear
A year ago I implemented 2d lighting in XNA using sprites. The sprites I used were created by placing a soft white photoshop brush on a transparant background.

The result was this: (lights only)

And this seemed right to me.

I returned to the subject this week to try replacing the sprites with a texture created with code and a formula:

As you can see, there is a black ring around every light.

This is the code I used for creating the textures:

```
int diameter = 250;
int radius = diameter / 2;

Color[] colors = new Color[diameter * diameter];

for (int y = 0; y < diameter; y++)
{
    for (int x = 0; x < diameter; x++)
    {
        Vector2 l = new Vector2(radius, radius) - new Vector2(x, y);
        float attenuation = MathHelper.Clamp(1 - Vector2.Dot(l / radius, l / radius), 0, 1);

        colors[x + y * diameter] = Color.White;
        colors[x + y * diameter].A = (byte)(attenuation * 255);
    }
}

Texture2D texture = new Texture2D(device, diameter, diameter);
texture.SetData(colors);

```

I got the attenuation formula from here.

Aside from that I now create the textures using code, the rest of the code has remained the same.

Where do the black rings come from, and how do I prevent them from appearing?

# Answer
> 2 votes
Okay, here are the settings you'll want to use to additive blending, plus some extra info in case anyone else wants to do something similar.

I'm not sure how to get this to work with pre-multiplied alpha (or if that's even necessary, since I'm guessing you plan to do mask-based lighting), so you'll want to make sure that if you have any resource based "brushes" (also known as "cookies") that you set the pre-multiplied alpha property like so:

I altered your texture declaration a bit:

```
_texture = new Texture2D(device,
                         diameter,
                         diameter,
                         false,
                         SurfaceFormat.Color);

```

Here's the set up:

```
protected override void LoadContent()
{
    // This is the texture we'll draw to,
    //     and then we'll use this texture as our mask.
    _canvas = new RenderTarget2D(GraphicsDevice,
                                 GraphicsDevice.Viewport.Width,
                                 GraphicsDevice.Viewport.Height,
                                 false,
                                 SurfaceFormat.Color,
                                 DepthFormat.None,
                                 0,
                                 RenderTargetUsage.PreserveContents);
    // This is a kind of additive blend.
    // It will clamp to the max channel once that channel reaches full "brightness."
    _addBlend = new BlendState
                    {
                        ColorSourceBlend = Blend.SourceAlpha,
                        AlphaSourceBlend = Blend.SourceAlpha,
                        ColorDestinationBlend = Blend.InverseSourceAlpha,
                        AlphaDestinationBlend = Blend.One
                    };
}

```

Then, your SpriteBatch.Begin call will look like this:

```
// SpriteSortMode is practically useless here.
_spriteBatch.Begin(SpriteSortMode.Immediate,
                   _addBlend, // <--
                   SamplerState.PointWrap,
                   DepthStencilState.None,
                   RasterizerState.CullNone);

```

---
Tags: xna, c#, 2d, lighting
---


# Question
Title: Reach concrete, numerical values for certain car values, in a car game
I am developing a rather complicated racing car management browser game, but I think this applies to any car game.

I have 10 values. Power, acceleration, etc. that can be easily quantified by using available data (hp, 1-100 kmh time). All is well, but I have 4 values (Handling, Braking, Transmission, Front/Back-Weight) that I'm not sure how to quantify.

Would I just say X car has Y brakes were Y = 20 (arbitrarily decided because I think this car brakes Y well) and then put it in a formula with car power and weight to reach this value, or does anyone have a better solution?

# Answer
> 1 votes
**Iterative empirical testing**. Add some test sliders to your GUI that control the various values you're trying to work out. Use common sense and estimate real world values to give your sliders as small a range as possible. Then, **play test**. Keep trying values, keep track of the ones you like.

---
Tags: racing, car
---


# Question
Title: Day and Night Cycles and Skybox Blending
I've been working on adding day/night cycles and random weather to my project using the Neoaxis engine. The day/night cycles itself is pretty simple, just rotating the "sun" light around the Y axis.

```
dayLength = 120; // How many real seconds to a game day
degreesPerSecond = 360f / dayLength;
sunY = 180f;  // Start on the horizon (6am)
currentHour = 6;
hourChange = 0;

```

Then on Tick for the sun

```
degreesPerTick = degreesPerSecond * Entity.TickDelta;

if(sunY >= 360f) {
    sunY = 0f;
} else {
    sunY += degreesPerTick;
}

hourChange += degPerTick;
if(hourChange >= 15f) {
    currentHour++;
    if(currentHour > 24) {
        currentHour = 1f;
        prevHour = 0f;
    }
hourChange = 0f;
}

sun.Rotation = new Angles(0, sunY, 0).ToQuat();

```

So, that got the sun moving nicely through the sky lighting up things as expected and calculating the hours based on each hour moving 15 degrees through the rotation.

I then started looking at how to implement the changes to the color of the skybox in order to have the nice orange skys during sunrise/sunset, blue as the day progresses and to black at night. Getting the color to change was easy but for some reason I can't seem to work out how to make the color lerp progress properly.

```
// Skybox changes
if( (currentHour >= 20 && currentHour <= 24) || (currentHour >= 0 && currentHour <= 4) ) {

    Engine.MapSystem.SkyBox.Instance.Color = skyNightColor;

} else if( currentHour >= 4 && currentHour < 7) {

    Engine.MapSystem.SkyBox.Instance.Color = skyMorningColor;

} else if( currentHour >= 7 && currentHour < 10 ) {

    Engine.MapSystem.SkyBox.Instance.Color = skyDayColor;

} else if( currentHour >= 10 && currentHour < 15 ) {

    Engine.MapSystem.SkyBox.Instance.Color = skyDayColor;

} else if( currentHour >= 15 && currentHour < 18) {

    Engine.MapSystem.SkyBox.Instance.Color = skyEveningColor;

} else if( currentHour >= 18 && currentHour < 20) {

    Engine.MapSystem.SkyBox.Instance.Color = skyNightColor;

}

```

What I am a little stuck on at the moment is how to work out the lerpAmount for each of the relevant places. I guess I need to somehow look at the start rotation of the lerp (e.g. 180) and the end position (e.g. 210) and then work out how to represent the current position as a value between 0 and 1 to use as the lerp value.

Is that the appropriate way to achieve what I am looking to do?

# Answer
Sure, you can do that. For instance, if you want the color to change from `skyNightColor` at 4:00 to `skyMorningColor` at 7:00, you could write some code like

```
if (currentHour >= 4 && currentHour < 7)
    color = lerp(skyNightColor, skyMorningColor, (currentHour - 4) / (7 - 4));

```

The expression `(currentHour - 4) / (7 - 4)` remaps `currentHour` linearly to zero at 4:00 and one at 7:00.

This assumes that `currentHour` is a float variable that varies continuously from 4 to 7 as time goes on. Right now you have it as an integer variable that changes discretely, but it'll probably be more useful as a float. (You can always cast it to an int if you need the integer hour.) Or you can also write the lerps in terms of `sunY`, if you prefer.

One enhancement you may want to do, depending on how fast time can run in your game, is replace the linear interpolation by cubic splines. If time runs slowly, it probably won't be noticable, but if time runs quickly (e.g. hours pass in a few seconds) then the sudden shift from one lerp to another can be noticable. Cubic splines such as Catmull-Rom splines will smooth this out. The spline control points would be the RGB values for your colors.
> 3 votes

---
Tags: c#, mathematics, graphics, skybox
---


# Question
Title: How are scripted camera usually managed?
I noticed that many open games (think platformers, adventure, action...) have very complex cameras that appear to mix both automatic placement most of the time, and sort of pre-placed camera locations.

How are these usually implemented? Is it just some sort of zone trigger that then launches an interpolation between the last camera state and the scripted camera for the zone, or are there more special details?

# Answer
There are several ways you can accomplish it. One way would be to use screen fade techniques to transition between the camera location swaps (current camera position & the camera track start/end positions) so that it blends nicely, which is generally great for cut scene type scenarios.

The other option would be to do as you described, interpolate from the camera's current position to the first camera track sequence node and applying some focal point so that the camera twists & spins as desired over the interpolation. Then begin the camera track sequence and when it ends, repeat the interpolation for the camera from the last track sequence node back to the camera's original position when the trigger was activated.
> 1 votes

---
Tags: camera, character
---


title: Using Unity 3D in LibGDX

text:
# Question
Title: Using Unity 3D in LibGDX
Is it possible to use Unity 3D engine with LibGDX when making Android game apps? Is it also possibly used for making 2D games using Unity 3D and LibGDX? I would like to know if it's possibly applicable in Java programming.

# Answer
> 3 votes
No, Unity and LibGDX would not be used together. Unity is capable of making 2D games, but not with LibGDX. You can program in Unity using something similar to Javascript, called Unityscript, but it's certainly not Java.

It sounds like you need to do significantly more research before embarking on anything too serious.

---
Tags: unity, java, libgdx
---


title: How to share matrix in HLSL?

text:
# Question
Title: How to share matrix in HLSL?
I am trying to share this across multiple effect files:

```
matrix worldMatrix : register(vs_4_0, b0);

```
1. If I set this from one effect file, will it effect every effect file which has the same type of variable assigned to that specific register?
2. What is the difference between this and the cbuffer struct?

# Answer
> 1 votes
If you bind a constant to one register, it will be there until something binds at the same place or if you bind that spot with null.

My approach of having constant buffer i want to "share" is to have a constant buffer struct in a include file. and then including that file into all the shaders im using. It's convenient and simple.

The difference with a single value and a cbuffer is how you bind the data and how you have to allocate the buffers. if you have a cbuffer, with 128 floats, you have to create a buffer thats equal of that size. while a single value wont let you create a register spot thats of a difference size than that type. Regularly, it's good to have a cbuffer with specific meanings. In other words, having a cbuffer that gets updated every frame, one that gets updated for each material and maybe one that contains some sort of Per second data.

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


# Question
Title: What is the purpose of inertial space and what are its uses?
I'm currently reading about left-handed and right-handed coordinate systems when working with 3D and it's all very fascinating. These systems are made up of world space, object space, and inertial space. I believe I have a firm grip on world space and object space, however I'm not entirely sure what inertial space is used for? If my understanding is correct - it is simply a way to convert local space to world space, and vice versa? Is inertial reference frame the same as inertial space?

# Answer
**Disclaimer**: *I am not a physics expert, neither I guarantee the following explanation to be entirely accurate, but I will try to make things simpler.*

First: Let's us break it down into two keywords, obviously space and interia.

Space (or a frame of reference) in 3D : is a combination of rotation and translation. So when we say a point is relative to a specific space, we mean that its coordinates are measured relative to that space orientation and translation. More on this here.

When you measure temperature you measure it relative to a certain reference (could be the zero or other value in your thermometer). When you say 10C you mean 10°C relative to 0°C where 0°C was defined as the freezing point of water. (Note: This is not entirely accurate more info here.

The same goes for bodies motion, we measure them relative to something else, whether it was an observer space or any other body space.

Inertial space is a reference frame that is itself not accelerating; that is said, objects being observed should appear appear to experience constant speed relative to each other.

Remember that constant speed means zero acceleration,

Newton's second law states:

> **F** = *mass* * **acceleration**

hence,

> **acceleration** = **F** / *mass*

And according to Newton's first law:

> When a object is viewed in an inertial reference frame, an object either is at rest or moves at a constant velocity, unless acted upon by an external force.

Inertial space is a space where Newton's laws holds true. This is important for calculations to remain simple. For example choosing a non-inertial space (an accelerating space) will make objects appear to have *ambient* acceleration even without having force acting on them, at this state Newtons laws of motion doesn't hold anymore.

It's easy to connect the first and the second law. If it was not for inertial space, neither will hold true.

An example of a non-inertial frame, an observer setting on an *accelerating* rotating disk, this will particularly complicate calculation, and will complicate even the slightest observations; such as the linear motion of two balls as observer from that location, (this needs some imagination) the balls will have acceleration relative to the observer, which makes Newton's first law no hold anymore.

## Inertial frame of reference in Gamedev and graphics

We just assume it exists, we never select a frame of reference that is accelerating, physics simulations are calculated relative to world coordinates, which is fixed. If you want to calculate physics relative to an accelerating camera (please don't mix the coordinates where things are rendered and the coordinates where physics is calculated) don't do that, the calculation will be redundantly complex. We never calculate physics an relative to an accelerating eye coordinates (even if you did you should select the coordinates that have Zero or constant velocity).

## Why did the chicken cross the road?

### Aristotle:

It is the nature of chickens to cross the road.

### Newton:

Because no force caused the chicken's state of uniform road crossing to change.

### Einstein:

Is the chicken crossing the road or is the road moving under the chicken?

More info here. And simple video introduction here.
> 3 votes

---
Tags: 3d, coordinates, terminology
---


title: GameServer UDP or TCP Java

text:
# Question
Title: GameServer UDP or TCP Java
This is a Java related question.

I've got this question and I searched on the internet but didn't really get any clear answer.

I want to develop a little multyplayer game which needs real time synchronization for a few clients. I don't really want to have a lot of clients, but I want to have the chance to create it for a greater scale later.

Seeing through some Links (also given here from stackexchange) I got the answer that UDP would be better, then others say TCP. I know it's sometimes more an opinion thing what you prefer most for yourself.

But I've developed some network games in the past (not proffessional ;) ) and used TCP. And I didn't really get a lagfree game, even for three clients (players)

I then used the new nio (asynch) network framework of java, but the lag just reduced a little bit.

So how can I develop a reliable Server-Client model? Using TCP or UDP? Or did I just end up developing a bad example and thats why my server-client communication lagged?

If someone has a good tutorial for developing a reliable java game server that would be nice.

Thank you

# Answer
> 3 votes
When I started looking at Network programming, I found the blog of Glenn Fiedler an excellent source of knowledge about real time network programming. He's starting with a broad discussion of whether to choose TCP or UDP for your game and covers details in later posts.

This would give you a starting point in the UDP vs TCP topic from a professional game developer (used to work for Sony, now working for respawn entertainment) but he is focussing on C++. So this is just for the abstract part of the question, not really helping with the Java part.

# Answer
> 3 votes
Some of the multiplayer games I have worked on used both. That is, TCP for messages that must be delivered, and UDP for information such as position updates where if one is missed the next one will be coming automatically. My own personal rule of thumb is if the information is something that I would ask to be resent if it were missed, to just use TCP.

One sneaky thing to check for lag with TCP is whether you have Nagling disabled. When Nagling is enabled and the client is sending TCP messages to the server frequently, with the server sending messages to the client less frequently, you probably won't notice much lag. If you have a situation where the server is sending more messages than the client is it can be a noticeable 200ms lag when Nagling is turned on. That is, the server will wait 200ms to send messages to the client unless the client sends a message. Check your client code as well to make sure it isn't Nagling the outgoing messages.

---
Tags: java, networking, server, client-server
---


# Question
Title: Marching cubes density function: noise sampling leaves holes in plane
I'm following the GPU Gems 3 chapter 1 (Generating Complex Procedural Terrains Using the GPU). The main difference is that I'm using the CPU for generating the mesh(es) based off of marching cubes. And I have this problem that I'm not sure how to solve or even debug.

In Figure 1-8, they start adding noise to the plane at y=0:

```
density += noiseVol.Sample(TrilinearRepeat, ws).x;

```

I tried to do the same thing, but I got a plane with island-like holes in it:

Here is my density function:

```
float densityFunction(Vector3 ws) {
    float density = -ws.y;
    density += noise[(int)ws.x, (int)ws.y, (int)ws.z];
    return density;
}

```

`noise` is a 3-dimensional float array of pink (Perlin) noise whose mean is 0. It has a frequency of 2 and 3 octaves with half persistence. Its standard deviation is ~ 0.2. And it varies around ±0.65.

The isolevel of the marching cubes algorithm is set to 0.

What could be causing this undesired effect?

# Answer
What I think is happening is that you are creating a marching cube for an area from \[0,0,0\] to \[10,10,10\] and the empty spots are the result of the plane being distorted away.

The density calculation seems to be simply moving up or down the points of the plane, this is causing some points to be below 0 and others above 0 (roughly 50/50). Your marching cubes is then sampling points at y=0 and finding that it should not put a triangle at this position.

Try putting your plane higher, this should work properly and is an easy enough change for a test. If that works then you need to make the marching cube area larger so it encompasses the entire distorted plane.
> 3 votes

---
Tags: unity, perlin-noise, marching-cubes
---


# Question
Title: How do I compute the point of a triangle-ray intersection?
I have a line (the direction vector of the player) and a triangle representing the face of a model (so composed of 3 points).

I can't find the mathematical operation to check if that vector is intersecting with this triangle, and how far from the player...

# Answer
In general, lines are a poor approximation of a user's movement because they don't account for the size of the player.

You want "sweep sphere triangle intersection", also called "capsule triangle intersection". http://xania.org/Games has a good overview of this.
> 3 votes

---
Tags: collision-detection, mathematics, vector, geometry, intersection
---


# Question
Title: How much mathematics is involved in video game development?
I'm average at maths. Maybe a tad below average. If I was going into a normal career I'd be fine. But I want to create video games. Is a career in video game development still on the cards for me?

I want to be a creative director, but I don't just want to write screenplays, create 3D models and draw concept art (areas I excel at.). I want to actually touch the code. I've been learning web development now for 8 months, and I understand pretty in depth concepts such as serverside fragment caching, and it would damn depressing to throw all those skills away and just hire some programmers when I move into video games. I want to develop alongside them. Is developing video games (with a team) similar to web development, in that it's all OOP and logic but with relatively little arithmetic? I'm not on about creating a 3D engine, I'm sure that's filled with physics and theorems of momentum, I'm on about simply *using* a ready made 3D engine.

**Do you need to be a *substantially* better at maths than most to develop video games?**

# Answer
> 6 votes
As Almo said, 3D game development requires some basic algebra, and so does 2D, but most of the actual development is just writing algoritms and loops. If you use an engine, depending on the engine, usually most of the physics will be taken care of, especially if you use a physics-based engine like Box2D.

AI in game development is often made of behavior trees, or logical paths that are chosen between based on previous choices, with some slight randomness.

To answer your main question: most game developers are slightly better than most at math, since they use it more than in some careers, but it should not be a problem for you if you manage to pass all of your high school and college math courses. Especially if you use an engine, you will not have to deal with most of the math. Also, there may be some modules (like the `math` module in Python) that will take care of things like rounding algorithms for you.

# Answer
> 2 votes
If you get into 3D game development, you had better know the basics of Linear Algebra so you can deal with vectors and matrices well.

Knowing basic calculus will help, as you'll want to know what derivatives are and how they relate to position, velocity, and acceleration.

Very strong knowledge of algebra will help, as you'll need to construct formulas for things.

# Answer
> 1 votes
*Substantially* better? Unless you're trying to create a 3D engine, no.

Since you do know programming and databases, you already have most of the necessary tech knowledge to make a game.

When you face a problem that needs math to solve, stop for a while, look for the already known solutions, test them and start learning from the basics so you can get there. I only actually learned geometry, radians, sin and cos when I had to make characters move in an angle. Before that, I had little idea what these things were.

Your school experience doesn't tell much about how good you are at math. I sucked at math back in school. Learning it when you have the code to mess with and test different values is a lot easier than learning some abstract equation in a classroom.

Also, beware of the left-right brain side myth. Your brain can learn as much math as anyone else's.

---
Tags: mathematics
---


# Question
Title: Are there copyrights for board game Risk and can I make the game, or similar, for mobile?
are there copyrights for board game Risk? It's popular and with lots of versions floating around, so I don't know if someone has rights or just for specific version. I'm not planning to make money with it, it would be a free game. If not, can I make something similar to that, and how much do I need to change it? I like the game a lot, it's for fun and learning purpose. Thx in advance :)

# Answer
> 4 votes
Game rules and mechanics cannot be copyrighted. Specific implementations, writings of the rules, names, and associated art CAN be copyrighted.

So if you don't call it Risk, and don't use any of Risk's art, I think you're fine.

The company I work for has had serious problems with dealing with the versions of our games people make for free thinking that alone makes it legal.

But as usual, I say this:

"Getting legal advice from random people on the Internet is not a good idea."

Do your own research, and consult a lawyer if you want to be sure.

---
Tags: mobile
---


# Question
Title: Isometric objects are mapped incorrect angle, but the map is fine. What am I missing?
I laid out my iso map and it's fine, but when I add my sprite actors they get located in the correct location but they are laying down not standing up. I tried rotating them on the z by 45 but then they moved to the wrong location.

Anyone have any idea what I'm doing wrong? looks like a steam roller ran over my object :-)

I'm going to try and upload pics.

https://picasaweb.google.com/114100917691803291674/20140120?authuser=0&feat=embedwebsite

\**correct location,but the image is laying down...

\**standing up, but wrong map position..

# Answer
> 0 votes
It seems like you're applying the map projection transformations to the objects that go on the map. If that's the case, draw the objects on the map without these transforms.

If you provide some code, I might be able to help you further.

# Answer
> 0 votes
I'm not familiar with libgdx, and you haven't provided any code showing what you're doing, but it looks like you're applying the transformations in the opposite order than you should. Swap the translation (tile position) and the rotation (orientation of the upright item), apply any needed small corrections and you'll be fine.

---
Tags: 2d, graphics, libgdx, isometric
---


# Question
Title: How can I load textured objects in jMonkey?
I am working on a project in jMonkey, and I managed to create boxes, spheres and such objects, and load textures form image files, but when I converted a Blender file to `.j3o` and imported it in my game, it shows up with no textures (it's just white).

The object does have textures, and they even show up in the jMonkey SDK. How do I load the textures that are already stored in the object file?

# Answer
> 3 votes
You should put all the images and other file in your Models/yourModel folder like this pic .

I have a model named `main` and many images and other files and i put all those in my Models/main folder.

then write this code:

```
    public class Main extends SimpleApplication {

    public static void main(String[] args) {
        Main app = new Main();
        app.start();
    }

    @Override
    public void simpleInitApp() {

    Spatial model = assetManager.loadModel("Models/main/main.j3o");

    Light sun = new DirectionalLight();
    rootNode.addLight(sun);
    rootNode.attachChild(model);
    }

```

I think it will work.

# Answer
> 1 votes
Try this:

```
1) In Blender - select the object's part to wrap with a texture and use the UV Mapping
2) Save the UV map file into the texture in the texture folder of the jme project.
3) Paste the texture on the pieces of the map file
4) In Blender - set the material and the texture as UV mapping.
5) Save the project as blender file (same folder)
6) Convert the blender file info j3o and import it on your scene.

```

In this video you can see how set the UV mapping, www.youtube.com/watch?v=obB9T3jXlak just remember that the mapping and the blender files must be saved in one of the project assets folders otherwise jme won't be able to see them.

---
Tags: java, textures
---


# Question
Title: Reduce render time for a tiled map in ThreeJS
I'm working on a WebGL game using Three.js, its been a few days and I found my first issue, render time on big maps.

The game runs great, there are even some AI mobs that run around randomly like crazy, the problem comes when the game has to display many tiles at once (being many around 900 (30x30) on my Computer), if I zoom in the game runs at 60 solid FPS, here's the game demo so you can watch it in action.

http://kuxtal.oruga.biz/

You can move around with the classic WASD or arrow keys and zoom in and out with the MouseWheel.

Right now I'm creating a map like this (The project's code name is Kuxtal):

I have a singleton called Kuxtal, from which all the magic happens, I create a Kuxtal.Instance, which holds the renderer, scene, camera, and some functions to work with them.

Then I create a Kuxtal.Map, to which I pass the width & height as parameters and it runs:

```
for (var i = 0; i < this.width; i++) { // map.width
    for (var j = 0; j < this.height; j++) { // map.height
        var type = Math.ceil(Math.random() * 3); // 1-Grass 2-Dirt 3-Something else
        var tile = new Kuxtal.Tile(type, i, j);

        this.tiles.push(tile);
    }
}

```

This is my Kuxtal.Tile Class:

```
Kuxtal.Tile = function(type, x, z) {
    this.type = type;
    this.x = x;
    this.y = Math.random(); // A random elevation between 0 and 1 les me see the grid and looks nice
    this.z = z;

    this.sprite = new THREE.Mesh(new THREE.CubeGeometry(Kuxtal.TILE_SIZE, 1, Kuxtal.TILE_SIZE), new THREE.MeshPhongMaterial({color: 0xFFFFFF, map: Kuxtal.getTexture("grass")}));
    this.sprite.position.set(SELF.x * Kuxtal.TILE_SIZE, SELF.y, SELF.z * Kuxtal.TILE_SIZE);
    this.sprite.receiveShadow = true;= THREE.RepeatWrapping;
}

```

And the tiles are added to the scene on this Kuxtal.Instance.loadMap(map) function:

```
map.tiles.forEach(function(tile) {
    SELF.scene.add(tile.sprite);
});

```

Any suggestions on how to improve the performance?

# Answer
great performance saving comes from caching geometries and materials.

In your case, create CubeGeometry and MeshPhongMaterial objects only once and then use them when creating tiles - each tile will be separate Mesh but all pointing to same instance of material and geometry objects.

Then do the same for all resources that can be reused - models, textures etc. Always think about what can you reuse and whether you really need to create a new object instance.

and btw - don't call those tile's meshes 'sprites' - it can be confusing as THREE.JS already has a type called Sprite.
> 4 votes

---
Tags: rendering, tiles, tilemap, efficiency, three.js
---


# Question
Title: map the section of a procedurally generated surface on a plane
I'll try to be as clearer as I can.

I have a surface on a 3D space which is not flat, it has hills and depths.

My goal would be intersect it with a plane so that I can map the section of the surface on it.

this is just an example with a tetrahedron, my surface is more complex:

My surface has just a set of vertexes so I was thinking that the solution would be theorically to map the intersection points of line segments bounding each vertex just above the plane with its corresponding one just below. Then I could connect the points on the plane like if I was drawing triangles on a flat surface.

My concern is also on what structures can I use to achieve this result? Does XNA give anything that could be of help? I saw the `Plane` structure and its explaination was quite clear. So next step would be to find the point belonging to a line segment laying on the plane, but sincerly I have no idea on how to proceed.

More than that, I also would like to be able to compute areas of "solid ground" mapped on the plane. But better to face one problem at time.

Hoping I made myself clar, I look forward to any suggestion

# Answer
> 2 votes
It would be simple and cheap to check if a given vertex is above or under a plane \[1\], but I guess it wouldn't help you to create the mesh of your terrain section.

I think you should have your surface triangulated first \[2\] and then check the intersection of each triangle with the desired plane \[3\].

For each intersecting triangle you should generate 2 other triangles. You should also store the intersection points for later use (see below).

For each non-intersecting triangle you should check if it's above of below the plane (this can also be part of the result of your chosen triangle x plane intersection method), because you only want to use the triangles below the plane.

The top cap of the intersected areas could be computed from the previously stored intersection points. Compute the top cap polygons \[4\], triangulate them \[5\] and generate the top cap meshes.

This way you should end up with the mesh of the terrain under the plane and the top cap meshes.

I guess you could optimize this solution, specially with the computation of the top cap polygon...

References:

\[1\] Point direction from a Plane:

http://www.gamedev.net/topic/106765-determining-if-a-point-is-in-front-of-or-behind-a-plane/ (Math)

\[2\] Famous libraries for tetrahedralization:

http://doc.cgal.org/latest/Triangulation\_3/index.html (C++)

http://wias-berlin.de/software/tetgen/ (C++)

\[3\] Triangle x Plane intersection algorithms:

https://stackoverflow.com/questions/3142469/determining-the-intersection-of-a-triangle-and-a-plane (Pseudo-code)

http://www.realtimerendering.com/intersections.html (C)

\[4\] Clustering + Convex Hull Algorithms:

http://www.alglib.net/dataanalysis/clustering.php (has a C# port)

https://stackoverflow.com/questions/16407533/translating-concave-hull-algorithm-to-c-sharp (another C# impl.)

\[5\] Ear-clipping triangulation:

http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf (Pseudo-code)

---
Tags: c#, xna-4.0, geometry
---


# Question
Title: Unity3d Run In Background setting not working in fullscreen standalone
I've ran in to an odd issue with my Unity3D game completely pausing in certain scenarios, even with the Run In Background player setting on.

For reference I'm on Windows 7 Ultimate using Unity 4.3.3

**In The Editor:** If I tab out of the editor while the game is running everything keeps working fine.

**\*In Windowed Mode:***** If I'm running the standalone in windowed mode and tab out, everything keeps working fine.

However, if I grab the top bar on the window to move the window around, the game pauses until I release the window. Nothing updates, nothing runs while it's paused.

**In Fullscreen Mode:** If I'm running the standalone in fullscreen mode and alt+tab out the game pauses. Not resuming until I tab back in to the game.

This is causing issues with the multiplayer aspects of my game, because the client stops sending messages to the server whenever they alt+tab out or move the window.

I know the graphics device is getting lost when I tab out, because I get this error in my log:

> HandleD3DDeviceLost HandleD3DDeviceLost: still lost Skipped rendering frame because GfxDevice is in invalid state (device lost)

But that should only cause the game to stop rendering, which is fine. I just need the update loop to continue.

# Answer
> 2 votes
So turns out this was a Unity bug. I reported it to Unity and they confirmed it for me. Not much to do besides wait for the next update.

---
Tags: unity, networking
---


# Question
Title: Using PhysX, how can I predict where I will need to generate procedural terrain collision shapes?
In this situation, I have terrain height values I generate procedurally. For rendering, I use the camera's position to generate an appropriate sized height map. For collision, however, I need to have height fields generated in areas where objects may intersect.

My current potential solution, which may be naive, is to iterate over all "awake" physics actors, use their bounds/extents and velocities to generate spheres in which they may reside after a physics update, then generate height values for ranges encompassing clustered groups of actors. Much of that data is likely already calculated by PhysX already, however.

Is there some API, maybe a set of queries, even callbacks from the spatial system, that I could use to predict where terrain height values will be needed?

# Answer
If you are generating meshes from your data for rendering you could pass the mesh off to PhysX as a collider Mesh. Meaning that physX and your renderer reference the same object cutting overhead.
> -1 votes

---
Tags: collision-detection, procedural-generation, terrain, physx
---


# Question
Title: does order of updates and renders matter?
I know in a game loop there needs to be an order like physics should update before rendering. So, I have created two separate functions: update and render and the game loops like below:

```
while(running) {
    clock.reset();
    for(auto system : systems) {
        system->checkForInput();
        system->update(clock.getElapsedTime());
    }

    for(auto system : systems)
        system->render();
}

```

Some systems have empty render function or empty update functions.

My question is, does the order of updates or renders matter? would it matter if gui is rendered before graphics, or input is updated after physics?

# Answer
> 15 votes
It's easiest to think of your order in a single frame, think of it as a series of dependencies.

* User input depends on nothing, so it goes first.
* Objects being updated depend on the user input, so they go second.
* Physics depend on the new updated objects, so it goes third.
* Rendering depends on the latest physics state and object updates, so it goes fourth.
* UI depends on the scene to already be rendered, so it goes fifth.

---
Tags: rendering, input, game-loop
---


# Question
Title: How many leaderboards can I have in Android via Google Play?
Question is simple. I have one game with multiple levels(say around 90) distributed amongts different amongst different worlds. Am I reading this right and it means I can only have 70 individual leaderboards or is there an alternative (grouping levels/worlds, api, etc)?

Just to be clear, additional information is:

I want to implement level based score, that is one leaderboard for each level (so players can see their score on a level by level basis), one leaderboard for each world, and one leaderboard for the whole game.

Thanks in advance.

# Answer
According to the official information about the leaderboard feature of the play-store, you can have up to a maximum of 70 leaderboards per application.

> Games can have multiple leaderboards, up to a maximum of 70. For example, a multi-level game might provide a different leaderboard for each level, and a racing game might have a separate leaderboard for each track.

When this isn't enough for your case, you will have to develop and host your own leaderboard system on your own server.
> 3 votes

---
Tags: android, multiplayer, leaderboards, google-play
---


# Question
Title: How do I efficiently check which object causes the most gravitational force in a list of thousands of objects?
I'm working on a proof-of-concept space engine, and one of its tasks is to find the object with the greatest sphere of influence towards the player; that is, the mass of the object, divided by the square root of the distance to the player. I don't see much optimization to do, as an octtree or a KDTree only works for points. Even though there might be a planet only a few thousand kilometers away, a black hole many million kilometers away might have a greater gravitational force on the player.

The current check is brute-force. I go through each object, and return the one with the highest gravitational pull on the player. I have around 10,000 objects to perform this check on, but I might increase this number to millions, later. Optimally, I want to perform the check during each frame, which currently lowers the frame rate from 1600 a second to around 100 a second, which is unacceptable.

---

A few ideas comes to mind, but none of which seems optimal:

1. Make the system run in its own thread. Great, if the user has a core they don't use for anything, but only gives more overhead if there are no more cores available.
2. Limiting the check to run only once every few frames, resulting in a better average frame rate. The frames that need to be checked will result in stuttering, so this seems like a bad road to go down.
3. Limiting the number of objects checked per frame, so no matter what, only 128 objects may be checked per frame. This has the advantages of solution 2, without the disadvantage of stuttering, as each frame is equally heavy. Still, the programmer in me somehow also dislikes this solution. Then again, game programming is quite different from what I have previously worked on.

---

I'm not asking solely just for the purpose of this specific system, but also to find the best practice for problems like this, where there must be a compromise between running frequently and performance.

Any suggestions specific to this problem, like how to optimize the function through a modified version of a KDTree, is also very much appreciated; but the question is directed more generally towards the best practice for such problem.

# Answer
> 3 votes
You can precompute most of this data with a spatial partitioning system. For each area in a KD-tree or quad-tree or spatial hash or whatever you want, you can compute the bodies that have meaningful influence over any that area.

To query which body has the highest influence on the player's ship, loop over all bodies influencing the area the ship is in. This is more or less identical to how you'd deal with collision in a grid where bodies might be larger than the width of the grid cells.

You can generate the initial data by adding all bodies to a single node in your tree. For any node that has more than `N` bodies (a tunable), split the node and recalculate the children's influencing bodies. Keep a minimum limit on the bodies; technically every body everywhere has influence on every other object but for gameplay reasons you can probably limit things to bodies that have more than `k` newtons (another tunable) of gravitational force. Basically the same as the usual octree/Kd-tree generation.

More simply, think of every body has having a bounding sphere encompassing its gravitational influence. Apply all the usual collision optimizations to that. Accept that bodies wont' have an infinite sphere of influence.

Or just use the GPU and generate a flow field.

# Answer
> 3 votes
If you're serious about attempting this, your best bet will be a combination of all 3 options, plus two more optimization strategies: spatial division (spatial hashing) and approximation. Kind of like mip-mapping you can treat far away objects as a single object.

Knowing how objects are divided in your universe or galaxy helps with approximation. Consider being somewhere within a particular solar system. In most solar systems it's fair to assume that 99% of the mass is in the star(s) - so unless you're getting "orbitally" close to a planet you can disregard any and all gravity from the system's planets. Including surrounding solar systems.

If you're somewhere between solar systems, again you can approximate each solar system's gravitational pull by disregarding all planetary masses and only consider the stars. Or provide a data structure for each solar system that provides the total mass of all the objects in the system, and use the center of the solar system as the center of gravity - at large distances whether a large object is several AU away from the center doesn't actually matter.

Considering that there are millions upon millions of solar systems in a galaxy, or perhaps you're even simulating multiple galaxies, then once again you can approximate by dividing your galaxy or galaxy clusters into evenly spaced sectors. Each sector stores the total combined mass contained within it, and the gravitational pull is the mass of the sector at its center. This is a close enough approximation even if you're in a neighboring sector.

Lastly, the force of gravity is a quadratic function. This means for any mass you have a certain distance at which its gravitational pull is no longer really relevant to your simulation. By tweaking this distance, you can easily sort out any and all objects whose mass to distance ratio is too high to have any effect on your simulation and simply discard them. You can store that information in a tree, perhaps sector-based, so that even when you do large jumps in position you get a fairly good set of masses that actually do have an effect on the simulation at that point in space.

Since you mentioned black holes, I wonder if you're maybe overestimate their effect. You may be surprised how little the gravitational pull of a black hole would have on our solar system if there were one within only 10 lightyears away or so. Or how heavy it would need to be to have a significant gravitational pull at this distance.

PS: If threading is required to run your game (smoothly or even just "playably"), then maybe just don't support single-core CPUs.

PPS: Also do some math on memory requirements. If you have 1 million mass objects in your galaxy and you could store them in 1 byte each, they would consume 1 Megabyte of memory. However you need to store their position in 3-dimensional space, which means 3 coordinates of data type double because the data range of floats may simply be too small to simulate the distances of objects in a galaxy. 3 times 8 bytes times 1 million makes 24 Megabytes.

More realistically each planet needs more than its position, probably its orientation, rotation, mass, what type of object it is, what it is composed of, who is living there, and so on. Make that 500 bytes per object and your memory requirement is 500 Megabytes. Make that 10 million objects and it's 5 Gigabytes.

CPU performance may actually be the smaller of your problems, you may soon find you'll need to swap sectors of planets in and out and replace them with just their approximate mass like I said earlier - if only to be able to actually keep your simulation's memory footprint in check.

---
Tags: c++, software-engineering
---


title: AndEngine - Smooth scaling on a sprite

text:
# Question
Title: AndEngine - Smooth scaling on a sprite
I'm trying to implement a pinch zoom on a sprite. I would like to get an effect like the SmoothCamera, but on a single sprite. I've managed to pinch zoom on the sprite by changing its scale, but the zoom is really fast and not smooth... it doesn't feel right.

This code is on my sprite :

```
public class BoardSprite extends Sprite implements IPinchZoomDetectorListener {
...
private float scale = 1;
    @Override
    public void onPinchZoom(PinchZoomDetector pPinchZoomDetector,
            TouchEvent pTouchEvent, float pZoomFactor) {
        float newScale = scale * pZoomFactor;
        if (newScale > 3) {
            newScale = 3;
        } else if ( newScale < 1) {
            newScale = 1;
        }

        scale = newScale;
        this.setScale(newScale);
    }

```

I'm looking for a way to improve this solution or for a better approach.

# Answer
> 2 votes
I have no experience with AndEngine, but from your code I suspect that since you update the `scale` variable with the result of `scale * pZoomFactor` every time `onPinchZoom` is called, you're basically turning this multiplication into an exponentiation.

To avoid this, simply delete the `scale = newScale;` assignment. But now, since you want to compute the scale relative to the scale at the beginning of the pinch zoom, you have to add a method that initializes `scale` to that value. The following might work:

```
private float scale = 1;

@Override
public void onPinchZoomStarted(PinchZoomDetector pPinchZoomDetector,
                               TouchEvent pSceneTouchEvent) {
    this.scale = Math.min(getScaleX(), getScaleY());
}

@Override
public void onPinchZoom(PinchZoomDetector pPinchZoomDetector,
                        TouchEvent pTouchEvent, float pZoomFactor) {
    float newScale = scale * pZoomFactor;
    if (newScale > 3) {
        newScale = 3;
    } else if (newScale < 1) {
        newScale = 1;
    }

    // scale = newScale;
    this.setScale(newScale);
}

```

# Answer
> 1 votes
Try setting a target scale, then ease towards that value, rather than setting the value directly. This is how the pinch zoom works in Angry Birds. It eases in over time.

The basic method is to increase the scale of your sprite by a fraction of the difference between the target scale and the current scale each update.

so in your onManagedUpdate(pUpdateSeconds) you'll add soemthing like this (writing from memory, code not tested)

```
float easeRate = 0.01; // Higher for faster easing;

float newscale = this.getScale() + (targetScale - this.getScale()) * easeRate * pUpdateSeconds/1000;

this.setScale(newscale);

```

---
Tags: java, android, sprites, andengine
---


title: Speed, delta time and movement

text:
# Question
Title: Speed, delta time and movement
```
player.vx = scroll_speed * dt

/* Update positions */
player.x += player.vx
player.y += player.vy

```

I have a delta time in miliseconds, and I was wondering how I can use it properly. I tried the above, but that makes the player go fast when the computer is fast, and the player go slow when the computer is slow. The same thing happens with jumping. The player can jump really high when the computer is faster.

This is sort of unfair, I think, because.

Should I be doing this someway else? Thanks.

# Answer
> 7 votes
Velocity is given in \[distance units\] per second, and you have a delta time in seconds (or at least you should, for all the reasons specified by Yakyb in his answer). The velocity tells you how far you want to travel in a second, so if your delta time from the previous frame is (for example) 0.1 seconds, and your velocity is 50 pixels/second, then the player should move 50 * 0.1 = 5 pixels in the new frame.

So, the simplest case would be to set your velocity to a constant value (e.g. 50), and either apply it or not based on whether the player is pushing the appropriate movement key / button / whatever:

```
vxMax = 50
if ([is the "move right" button down?])
{
    player.vx = vxMax
}
else
{
    player.vx = 0
}
player.x += player.vx * dt

// Ditto for player.vy and player.y

```

This is a good start, but it has some problems. First, movement is will be jerky -- the player will start and stop moving instantly, and always move at a constant velocity. You probably want to gradually increase the velocity from 0 up to the maximum velocity over several frames while the movement key is held, and then gradually decelerate to back to velocity=0 when the key is released.

This approach will also break down when the delta time is very large. For example, if you hit a sudden unrelated system performance hitch that causes one frame to take ten seconds to render, then your delta time will be (relatively) huge. Unless your collision detection code is *very* careful, this will cause the player to jump instantly across the game world, passing through any walls and obstacles in between. There are ways to avoid this; you can detect abnormally large time steps and break them down internally into several smaller time steps, checking for collisions every step of the way. Or you can look into continuous collision detection, swept-volume collision detection...but that's way beyond the scope of this question.

# Answer
> 3 votes
dt shouldn't be in milliseconds

if your speed is how much you move per second, you dt should be representative of seconds

i.e. if you are running at 60fps it should take you 60 frame cycles to move one unit of your velocity.

therefore your dt should be

(time since last frame in milliseconds) / 1000

or simply how much as a percentage of one second has the game moved on since the last frame

in the example of 60fps

16.6666 / 1000

# Answer
> 1 votes
This is a bit more complicated.

Basically, you want to keep a variable that every frame accumulates the time it takes the game to render, and when it comes to game logic (especially physics), divide it into fixed discrete chunks and interpolate the renderable state based on the remainder.

This is a canonical article describing this technique along with several other approaches for managing delta time in game loops, you **really, really should read this**:

http://gafferongames.com/game-physics/fix-your-timestep/

---
Tags: game-loop
---


# Question
Title: How can I extract the Geometry from a j3o file?
I created a blender file and then converted it into the j3o file. The only way to load the 3d structure in the game is through a Spacial object:

```
Spatial towerModel = assetManager.loadModel("Textures/tower.j3o");

```

Initially the tower in the scene was composed by a simple Geometry:

```
new Geometry("Tower." + index, new Box(X_SIZE, Y_SIZE, Z_SIZE));

```

To substitute this implementation with a proper 3d tower I need to use the Gemetry object from the 3jo.

How can I extract the Geometry from the j3o file?

# Answer
> 1 votes
The Spatial given to you from the loadModel method is most likely a Node. You'll have to traverse that node's children (and possibly grand-children) to get to the Geometry, which you will have to cast from one of the child Spatials.

I've not got the code before me right now, so I can't show you, but looking at the Javadoc it should be pretty simple (a bit of recursion should help).

---
Tags: java, jmonkeyengine
---


# Question
Title: How to set a body to a specific position using Andengine
I'm developing a game with a single player and multiplayer mode. Lets say I have walls (static bodies), vehicles (dynamic bodies) and bullets (dynamic bodies).

It works fine to control my own vehicle using `vehicleBody.setLinearVelocity(velocityX, velocityY);`. The vehicle can collide with walls and bullets as expected. Now I like to move the enemy vehicles in multiplayer mode. When I use the same method to move the body by its velocity values (in multiplayer mode), the vehicles get out of sync really quickly, means they don't have the same position on all devices because some data packages get lost.

What I'm currently doing is the following:

**On device #1:**

1) I move the body using `setLinearVelocity`

2) Then I get the X and Y position of the body and send a data package to the other device

**On device #2:**

3) I receive the data package and set the position of the body. I tried different ways, hopefully you can tell me the best way or alternatives I did not try yet:

* using `vehicleBody.setTransform(...)`:

```
activity.runOnUpdateThread(new Runnable() {
    @Override
    public void run() {
        vehicleBody.setTransform(new Vector2(newPosX, newPosY), angle);
    }
});

```
* I also tried using `MouseJoint` (based on that tutorial), but somehow the body was bouncing randomly to the next position. Sometimes it was working great, but when I restarted the game the vehicle of the enemy started bouncing again. Maybe I failed to setup the parameters. Here is what I used:

```
public MouseJoint createMouseJoint(float newPosX, float newPosY) {
    final float PIXEL_TO_METER_RATIO = PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
    Vector2 v = vehicleBody.getWorldPoint(
            new Vector2(newPosX / PIXEL_TO_METER_RATIO, newPosY / PIXEL_TO_METER_RATIO));

    MouseJointDef mjd = new MouseJointDef();
    mjd.bodyA = groundBody;
    mjd.bodyB = vehicleBody;
    mjd.dampingRatio = 0.2f;
    mjd.frequencyHz = 30;
    mjd.maxForce = (float) (1000.0f * vehicleBody.getMass());
    mjd.collideConnected = true;
    mjd.target.set(v);

    return (MouseJoint) mScene.mPhysicsWorld.createJoint(mjd);
}

```

Before I've used bodies I was using simple sprites and it worked perfectly. I sent data packages to the other device(s) and set the position and rotation of the enemy vehicle by using `vehicleSprite.setX(newPosX)`, `vehicleSprite.setY(newPosY)` and `vehicleSprite.setRotation(angle)`. Compared to that, bodies seem to be very complicated. So how I can I keep positions synced without bouncing?

By the way, on some pages I read about using `KinematicBody` instead of `DynamicBody` for a vehicle. What is the advantage? My vehicle needs to collide with the environment, so I think `DynamicBody` is the correct choice, isn't it?

# Answer
> 1 votes
MouseJoint is not a good idea, it will get out of sync too. It's really meant to be used to make the body move towards the point. `setTransform` is exactly the same as setting the position and rotation of the Sprite. You just have to be setting the coordinates in meters not pixels.

I am not an expert on multiplayer, but the latency will influence it always. You should probably send the velocity AND coordinates. Each time you should call `setTransform` and `setLinearVelocity`. So the body will be correcting its position with each update and also moving approximately the correct directions between updates.

in any case you should be doing all checks on a server (one of the client can be the server) and clients should be only presenting the results.

---

Kinematic body is not influenced by gravity and other forces. It's like a static body that can move by setting the velocity. If you bump into it, it won't change its velocity.

---
Tags: box2d, andengine, body
---


# Question
Title: Pygame - CollideRect - But How Do They Collide?
I'm having some trouble figuring out how I can handle collisions that are specifically colliding on the *top* or *bottom* a rect. How can specify those collisions?

Here's a little code snippet to give you an idea of my approach. As it is now it doesn't matter where it collides.

```
# the ball has hit one of the paddles. send it back in another direction.
    if paddleRect.colliderect(ballRect) or paddle2Rect.colliderect(ballRect):
        ballHitPaddle.play()
        if directionOfBall == 'upleft':
            directionOfBall = 'upright'
        elif directionOfBall == 'upright':
            directionOfBall = 'upleft'
        elif directionOfBall == 'downleft':
            directionOfBall = 'downright'
        elif directionOfBall == 'downright':
            directionOfBall = 'downleft'

```

Thanks in advance.

```
**EDIT**

Paddle rect:

 top
 ____
|    |
|    |
|    | Sides
|    |
 ----
bottom

```

I need to know if the ball has hit either the top or the bottom.

# Answer
> 3 votes
# Makeup of angles:

Basically you have to look at the angles between the center of the rectangle you are using for a paddle and the center of the rectangle of the ball (can also be a point since we collapse the ball rectangle into a point anyways).

The angle between the center points is then compared to the quadrants given by the corner points of the paddle (this gives left, right, up, down). The following program does just that with a bit of normalization to make lookup in the array easier.

# Test program

The part relevant to your question is really the DirRect class.

```
import pygame
import math

class DirRect(pygame.Rect):
    def direction_to_rect(self, drect):
        ar = math.atan2(self.centery - self.top, self.right - self.centerx) # half of the angle of the right side
        # construct the corner angles into an array to search for index such that the index indicates direction
        # this is normalized into [0, 2π] to make searches easier (no negative numbers and stuff)
        dirint = [ 2*ar, math.pi, math.pi+2*ar, 2*math.pi]
        # calculate angle towars the center of the other rectangle, + ar for normalization into
        ad = math.atan2(self.centery - drect.centery, drect.centerx - self.centerx) + ar
        # again normalization, sincen atan2 ouputs values in the range of [-π,π]
        if ad < 0:
            ad = 2*math.pi + ad
        # search for the quadrant we are in and return it
        for i in xrange(len(dirint)):
            if ad < dirint[i]:
                return i
        # just in case -1 as error indicator
        return -1

pygame.init()

screen = pygame.display.set_mode([400,400])
screen.fill([255,255,255])

# This is the paddle
paddle = DirRect( (150,150),(40,20) )
# colorize directional information
colors = [ (255,0,0), #right
           (0,255,0), #up
           (0,0,255), #left
           (0,0,0), #down
           (255,255,255) # error = -1
           ]

#show direction for every point
dsurf = pygame.display.get_surface()
for x in xrange(dsurf.get_width()):
    for y in xrange(dsurf.get_height()):
        prect = pygame.Rect((x,y),(0,0))
        dsurf.set_at( (x,y), colors[paddle.direction_to_rect(prect)])
#show paddle
pygame.draw.rect( dsurf, (128,128,128), paddle, 1)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False
    pygame.display.update()

pygame.quit()

```

# Answer
> 1 votes
```
def on_collide(paddle, ball):
    # we collided, so which side? Args are the `Rect`s of paddle and ball.
    if paddle.centery < ball.centery:
        print("paddle bottom")
    elif paddle.centery > ball.centery:
        print("paddle top")

    if paddle.centerx < ball.centerx:
        print("paddle right")
    elif paddle.centerx > ball.centerx:
        print("paddle left")

```

---
Tags: collision-detection, python, pygame
---


# Question
Title: Use large image individually, or in TextureAtlas?
Does it make any sense to include a large image (with dimensions of say 1920x1080) in a `TextureAtlas` and then use it with libgdx for example?

Or should I rather use it individually and include the .png file into the assets folder as it is?

Thank you.

# Answer
Use it individually. Texture atlases are used to gain efficiency by minimising texture swaps for many small textures, and avoiding wastage due to textures having to be bumped up in size to dimensions that are a power-of-two. A single image on an atlas gains you nothing except more book-keeping, and if the atlases are required to be power-of-two in size, your example image would need to be 2048x2048. That's a lot of wasted space.

The original tags included Android, which brings some extra factors to the discussion:

A 1920 x 1080 image will most likely need to be compressed to work on Android anyway, which comes with a need for power-of-two sizing. PNG is not a native format, so any PNG images will have to be converted and probably compressed before use. So even storing and using it individually, for loading and rendering it will be bumped up to 2048x2048 before it's compressed. You could use it at its native resolution uncompressed, but it would be **massive** in memory, and you probably want to avoid that. In practice we've always used compression on full-screen backdrops, but left texture atlases uncompressed (because the quality drop is far more noticeable on the smaller sprites); that's a pretty common policy for most places I believe.
> 3 votes

# Answer
First of all 1920x1080 is not power of two, even if your card support NPOT textures I think it's a best practice to use a POT texture.

Second let's calculate the size in bytes. `1920 * 1080 * 4 = 8294400 bytes` that is around 8mb of memory. Since the answer is tagged as android I assume you are talking about a mobile platform. A lot of the mobile platforms can't handle more that 2048\*2048Citation needed.

So if you are talking about it as a stand alone texture that's big! If it was part of an Atlas that's even worse, I assume the atlas will be much bigger.

My advise use it as stand alone. And make sure you use don't alot of memory, you might need to scale it down.
> 3 votes

---
Tags: android, image, texture-atlas
---