title: TiledMap not drawing completely

text:
# Question
Title: TiledMap not drawing completely
While attempting to constrain camera scrolling to within the `TiledMap` I discovered that it seems the renderer for the map is not drawing the entire map. The map is 1600x960px so one would assume the setting the camera position to `1600, 960, 0` would result in the top right corner of the map to be centered, however to actually center the map (I had to do some trial and error for this) the coordinates are closer to `1175, 740, 0`.

The map is made of 25x15 tiles and each tile is 64x64px. I initialize the map and renderer like this:

```
    tileMap = new TmxMapLoader().load("maps/" + file);
    renderer = new OrthogonalTiledMapRenderer(tileMap, stage.getBatch());
    renderer.setView((OrthographicCamera) stage.getCamera());

```

Then to render I just call `renderer.render()`.

Any idea why this could be happening and how to fix it?

# Answer
> 1 votes
So you need to call `renderer.setView(orthoCamera)` to reset the tile map drawing view. Then don't forget to also call `camera.update()` after you do anything to it.

---
Tags: java, libgdx, camera
---


title: Scaling an SDL Surface

text:
# Question
Title: Scaling an SDL Surface
I want to create a button for a game's UI. The background uses a gradient and then I blit a surface on top of the gradient and use SDL\_SetColorKey to delete the unwanted pixels. The surfaces are not the same size: the clipping mask is 200 x 50 and the gradient 1 x 50, so I need to stretch the gradient to the same width of the cliping mask, I can't use a wider image because the purpose of doing this is to save memory and storage and using the same gradient image on multiple clipping\_masks of different widths.

I found I can use SDL\_BlitScaled but I need to blit the surface to itself and it appears to be useless because the surface remains the same size, am I doing something wrong? Is there a way to do it without blitting the surface to itself?

```
SDL_Rect final_size;
final_size.w = 200;
final_size.h = 50;
final_size.x = 0;
final_size.y = 0;
SDL_BlitScaled(gradient_surface, NULL, gradient_surface, &final_size);
//do some stuff with those textures
SDL_CreateTextureFromSurface(renderer, final_button_surface);

```

# Answer
> 3 votes
SDL2 is very capable of doing exactly what you ask. SDL2 is also more efficient and has much more utility. I highly recommend upgrading to SDL2 by following the instructions provided in the Migration Guide on SDL Wiki.

EDIT: It took me a few days to migrate my project from SDL 1.2 to 2.0.3; most of the migration process was changing from SDL\_Surface to SDL\_Texture and figuring out how the new SDL\_Renderer and SDL\_Window types work together.

---
Tags: sdl, c, interface
---


# Question
Title: How do I combine matrix transformation with non-uniform screen scaling in Flash?
I'm using a Flash transformation matrix for affine transformation.

I have a rectangular image being rotated and scaled (in 2D). There are two sets of scaling variables, ScreenScaleX and ScreenScaleY, and ScaleX and ScaleY, as well as a counter-clockwise rotation angle, theta. ScreenScaleX and ScreenScaleY are the scaling factors of the window; they should be applied in directions of the *original* X and Y axes after rotating the image. ScaleX and ScaleY should be applied in the *new* X and Y directions after rotating the image.

For example: if theta is 90 degrees, ScreenScaleX and ScreenScaleY will still stretch in the direction of the original X/Y axes, but now ScaleY will stretch in the screen's X direction, and ScaleX will stretch in the screen's Y direction.

I think I can accomplish this with some combination of scaling, rotation, and skewing, but I'm struggling to figure out what the matrix would look like. How would I construct a matrix from these variables in order to perform this transformation?

# Answer
> 1 votes
I think I solved it. The answer is:

```
var matrix = new Matrix();
var cos = Math.cos(angle);
var sin = Math.sin(angle);
matrix.a = scaleX * cos * screenScaleX;
matrix.b = scaleX * sin * screenScaleY;
matrix.c = -scaleY * sin * screenScaleX;
matrix.d = scaleY * cos * screenScaleY;

```

This way, the screen can use non-uniform scaling without distorting rotated images.

---
Tags: flash, matrix, actionscript-3, geometry, transformation
---


# Question
Title: Is there a build-in function to count the amount of sprites drawn by SpriteBatch per frame?
I'm hoping to find out how many sprites are on the screen at any given time.

In other words, is it possible to find out how many times `spriteBatch.Draw();` is called between `spriteBatch.Begin();` and `spriteBatch.End();`?

I'm looking for a build-in function. Although I'm more then happy to write something myself, I'd rather not reinvent the wheel, and maybe I've overlooked something.

# Answer
There is no built-in function.

You're using MonoGame, so you could just modify the MonoGame source to do exactly what you want.

You could also use reflection to get access to the internal `SpriteBatch` member that holds the current count. In XNA it's the `spriteQueueCount` field. MonoGame seems to be more complicated - look at the source code to determine what to reflect on.

Otherwise, the "nicest" thing to do, code-wise, would be to make a wrapper function for `Draw`. Or simply manually increment your own counter every time you call `Draw`.

Note that this will give you the number of sprites drawn - which is not necessaraly the same as the number that appear "on screen".

If you're just trying to measure performance during development, it might be better to do something at the GPU level (I used to recommend PIX for this, with XNA on DirectX 9 - you'll have to figure out what works best for MonoGame on your target platform).
> 1 votes

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


# Question
Title: What happen if I try to run OpenGL 4.4 code on an unsupported graphic card?
I'm learning OpenGL because I'd like to build my own engine. I'd like to know what happens if I try to run OpenGL 4.4 code (the latest version at the moment of writing) on an unsupported graphic card ? (I mean for example a graphic card that support up to 4.1 OpenGL). Does it fails even to start ? or, it start but fails to render ?

Thank you very much.

# Answer
> 5 votes
In C and C++, you just wouldn't get the functions to run it. You'd send the request for a 4.4 context and get a NULL context back (indicating that it wasn't created.) You'd make a `wglGetProcAddress` call and get NULL back for the function that you requested an address to.

If the hardware doesn't support it then your stuck without. There might be a chance that the user could upgrade their graphics drivers, but if the card is to old then the company will just stop updating them. They have no reason to worry about a 5 year old graphics card, when they have 10 to worry about just in the last 2 years. Then there's no guarantee that the graphics card would be able to handle such things. A major thing that changed in OpenGL is they moved to a shader-programmable pipeline. I'm sure that had quite an effect on how the hardware needed to be made. And with new APIs and features coming out, there where a lot of things back then that I doubt they would've been prepared for in the hardware design, so it's quite likely that some graphics cards are just stuck with insufficient support.

If you implemented OpenGL in software, you could use all functions that you implemented. But hardware acceleration would be difficult. You might be able to speed it up using things like OpenCL, and CUDA. Though, those are newer technologies as-well.

If you want hardware support, I would be to create an abstraction layer for your application to use. Create a basic interface class, with pure virtual functions, that has calls to all the function that you need (I'll call it `GraphicsAPI`). Give it the basic functions you need, like `AttachToWindow`, `RenderObject`, `CompileShader`, `UseShader`, `CreateTexture`, etc. Then create a class called `OGL44` that inherits `GraphicsAPI`, and implements all of those functions using the OpenGL 4.4 API. You could then create a class that inherits `GraphicsAPI` and implements functions according to the OpenGL 3.0 API, and use them interchangeably by passing them as a `GraphicsAPI` class to where it's needed. You could also look into how other APIs, like Ogre3D, handle it. They have the same problem to work-around.

---
Tags: opengl
---


# Question
Title: Make a square flickering at a preset frequency
I'm working on a medi-sci project where I want the patient to use brainwaves to exercise control the environment.

The environmnet is a 2D game where the game character is to be controlled by 2 flickering squares. Each square are supposed to be on different frequencies e.g. 7Hz and 9Hz. They should flicker between black and white.

These frequencies will be measured on the brain and used to move the characters in a BCI solution. The project is being made in Unity and in c#.

I tried to use the animator and the Update function in Unity to get a flickering but it didn't work out (Read: It was very bad) because when the game became slow so did the flickering. I couldn't use that.

A friend told me that there's a difference between CRT and LCD screens so the refresh rate is different and can't be used the same way. I was also told to look into Timer.Interval in C# (or just the Timer class) and use that to switch between black and white squares to get the right frequency.

Is there anyone who could show me how to do this the right way in unity with C#? I mean how can I use Timers.Interval or System.Timers.Timer (or something else in the Timer class) to give me the right frequency in Unity?

I would prefer an example because I can't see any way of getting to the solution at all...

# Answer
> 0 votes
First off CRT and LCD are different in may ways. Though I'm not sure how their refresh rate changes. I can say, with absolute certainty, that their difference in refresh systems is not something that is used. Nor is it something that you can change, or something that will be effected by game-code (aside from maybe adjusting the refresh rate, if you felt like going to an extreme.) All you can do is pump out an image to it though the cable connected to your computer, after that all you can do is hope the monitor displays it.

If your pumping out images to fast for the monitor to display them, then it drops the frame. If your pumping out images slower than it's displaying them, then it continues to display the same frame (for a brief time.)

---

There are two options that I'm seeing:

1. http://docs.unity3d.com/ScriptReference/Time-deltaTime.html

Delta time indicates the number of seconds that have passed between this frame and the last frame. Since it's a float variable, you can use it to determine the amount of time that has lapsed for your Hz cycle. This, however, is frame-rate dependent. Granted, if your game is going around 9Hz (which would be 9fps), it's not going to be playable anyway. Typically, you want a minimum of 20Hz before a game is considered playable. 30Hz is standard. 60Hz is ideal (It's the refresh-rate of most modern monitors.)

2. FixedUpdate() - http://docs.unity3d.com/Manual/class-TimeManager.html

FixedUpdate gets called every `x.y` seconds regardless of frame-rate (frame-rate might be sacrificed to ensure it.) Should be fairly reliable. You then have the problem, however, of if that frame gets rendered. Even if it updates, if your frame-rate is slow enough to skip an entire 9Hz cycle, you might not see it update. (But it will cycle regardless.)

---

**HOWEVER**, I personally would say to figure out why your frame-rate is dropping low enough to make it problematic. There should be diagnostic tools somewhere in unity, find your-self the bottlenecks and fix them. If the games becoming slow-enough to be visible in a 9Hz cycle, then it's a fairly major frame-rate drop.

---

Edit:

Okay, Here is the basic theory. You have Hz, Hz is a unit of measurement that records the number of cycles per second. So saying you want something to switch on and off at 9 Hz, means you want it to turn on and off 9 times a second.

So we need some way to express the on/off oscillation according to time. The easiest means of oscillation we have access to is a sine or cosine wave.

If we are to use that, we end up with a value that goes from 0, to 1, to 0, to -1, to 0...

However, we only need on and off. We don't need every value between -1 and 1. We can simplify it by saying "This half of the cycle means on, and this half of the cycle means off." To divide it into half, we'll use the value 0 as our switch point. Resulting in something like:

All this theory coming down to the code:

```
using UnityEngine;
using System.Collections;

public class flicker : MonoBehaviour
{
    public Sprite white;
    public Sprite black;
    public SpriteRenderer ren;
    public float cycleHz; // Hz, the mesurement of cycles.

    float dtime = 0; // delta time

    // Update is called once per frame
    void Update()
    {
        // update frequency time-step
        dtime += Time.deltaTime;

        // Sample the waveform at a specific time.
        float wave = Mathf.Sin( (dtime * 2.0f * Mathf.PI) * cycleHz);

        print (dtime);
        print (wave);

        // Cycle between sprites based on the waveform.
        if (wave > 0.0f)
        {
            print ("Black");
        }
        else
        {
            print ("White");
        }

        // prevents dtime from climbing to infinity,
        // by stepping it back in the waveform to a point
        // of equal value.
        if (wave == 0.0f)
        {
            dtime = 0.0f;
        }
    }
}

```

Bonus Fun:

* What happens when we make it so that the switch point is 0.5?
* What if it's cosine instead of sine?
* What happens if we make it *tangent* instead of sine or cosine?

# Answer
> 0 votes
If you're not dead-set on flickering, there's a simple solution to this, which is to use a trig/wave method (like `sin` or `cos`). These will produce a continuous, even oscillation (which, at a high enough frequency, may appear similar to flickering).

I don't know enough about Unity to suggest why it didn't work. What I think is that you're probably using total game time (instead of time since the last draw/update call), or your update interval (since the last frame) is too big.

If you decide to use trigonometric functions, you can just use something like the current time (total number of seconds since game start or some other date/time) as the value to pass into the sine/cosine method.

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


# Question
Title: Efficiently detecting objects inside multiple radius
I would like to create a game for mobile that require to calculate multiple time by seconds which moving objects are in the radius of moving points. The game is highly inspired from Gratuitous Space Battles, the radius being from the weapons. Thus, I would like to know if it's realist to expect to be able to know among 1000 moving objects, in which radius they are among 1000 moving points 100 times per seconds on an average android device. In term of complexity, if there is an algorithm better than O(N\*M), N being the number of moving objects and M the number of radius from M moving center and if an algorithm can benefit from the fact that the moving objects are near their precedent position.

# Answer
> 4 votes
You might be interested in a so called quad tree. A quad tree is basically a structure where you divide the area in boxes and put all objects in lists on these boxes. You can then check for collisions only in the boxes that are actually in range of the object. The advantage of quad trees over say 2d arrays is that you they scale very well, if you have a large area with nothing in it and a small area with a lot in it then most other solutions will not work as well. This is how to maintain a simplified quad tree:

1 If a box loses an object check if it's now to small, if it is merge it with another square

2 if a box gains an object see if it's now to large if it is split, if you split an object always do so by spiting it over the largest side (a 10-20 should be split along side the 20 axis) and at such a position that both boxes now contain an equal number of objects.

3 Every box stores in it all of it's neighboring boxes and each object stores in which square it currently is.

Now if you want to check if an object is in range start by checking if it's box is in range if it is check for each of the objects in the box if they are in range and then check repeat this check for all neighboring boxes (recursive).

This does however carry a bit of overhead so if your range is likely to be larger then say 25% of the map it usually slows things down.

I think that what a game as Gratuitous Space Battles (at least for ai) does it first check if a ship is in range (any part of a ship is in range use a square for this) and then check each individual part. What most real games do is use a combination where large scale AI calculations are ran on the second system and the first is used for collision detection (and short ranged stuff).

# Answer
> 3 votes
## First, do a preselection

When a weapon has a low range, it usually doesn't make much sense to check it for collisions with objects at the other end of the world. You can drastically reduce the number of comparisons when you can narrow it down to objects in local vicinity.

One option is to use a two-dimensional tree structure. These usually allow you to very efficiently iterate all objects in a rectangular area. When you first get all objects in a box as large as your circle and then check each result accurately with the pythagorean theoreme, you can often save a lot of CPU cycles.

Another alternative to a 2d tree which is less elegant but easier to implement is a chunk-based approach. Divide the map into a raster of chunks `n` pixels wide and high represented by a two-dimensional array of object-lists. When an object moves from one chunk to another, remove it from the list of the old chunk and add it to that of the new chunk. A low-range attack should usually only be able to affect a limited number of chunks, so you only need to check the object-lists of a few adjacent ones.

The ideal value for `n` depends on your game. When you pick it too large, you still need to check too many objects. When you pick it too small, you spend too many cycles managing chunk-transitions. The ideal size depends on how much your objects move around, how large the distances of usual range-checks are and how likely objects are to form clusters.

## Second, store ranges already squared

On most platforms, the most expensive part of the pythagorean theorem `dist = sqrt(distx * distx + disty * disty)` is calculating the square-root. You can optimize this by calculating the square of the range of every weapon once in advance and then skip the square-root calculation. This, however, only works under the assumption that your range-checks are simply binary in-range-or-not-in-range and you don't need the exact distance.

## Third, do you really need to check everything for everything 100 times per second?

You definitely want to run your movement at the full framerate so the animation looks fluid. But that doesn't mean that all interactions between objects also need to be checked that often. Checking for collisions only every n-th frame can sometimes be enough for some use-cases.

For AI, for example, it can make sense to run the decision-making only once per second. This results in a delayed reaction to events which even feels more natural and human than an instant reaction.

---
Tags: android, algorithm
---


title: Odd Jumping Behavior?

text:
# Question
Title: Odd Jumping Behavior?
While testing my player's jumpinig algorithm, I've come across two odd problems.

1) My player's hard-coded jump height is always much greater (roughly 1.5 times) than the in-game result, making me enter completely abstract numbers for the hard-coded value.

2) My player's jump height increases with lower FPS. At 60 FPS, the jump height was found to be 237, and at 30 FPS it was 269.

This has me completely bumfuzzled. I've been using this article pretty heavily while implementing my jumping function which can be seen below.

```
Player::Player(param1, param2, int init_jumpheight, double init_jumptime, param3..)
{
  jumpheight = init_jumpheight;
  jumptime = init_jumptime;

  m_gravity = -(2 * jumpheight) / (jumptime*jumptime);
  // other stuff
}

void Player::handleJump()
{
   if(animState != JUMPRISE && animState != JUMPFALL)
   {
      animState = JUMPRISE;
      jumpspeed = 2*jumpheight/jumptime;
      jumpTimer.start();
   }
   else if(animState == JUMPRISE || animState == JUMPFALL)
   {
      jumpspeed += m_gravity*jumpTimer.get_ticks()/1000;
      int yshift = jumpspeed*jumpTimer.get_ticks()/1000;

      if(DEBUGMODE) printf("%0.2f\t%d\t%d\t%d\n",jumpspeed,yshift,jumpTimer.get_ticks(),m_coords.y);

      shifty(-yshift);
      jumpTimer.start();
      if(yshift < 0 && animState != JUMPFALL) animState = JUMPFALL;
   }
}

```

And here's my console log (the bit that records the details of the jump):

```
1258.40 20      16      1520
1219.40 18      15      1502
1180.40 17      15      1486
1146.60 14      13      1471
1107.60 16      15      1459
1068.60 16      15      1445
1034.80 13      13      1431
1001.00 13      13      1420
962.00  14      15      1409
923.00  13      15      1397
886.60  12      14      1386
852.80  11      13      1376
816.40  11      14      1367
777.40  11      15      1358
738.40  11      15      1349
704.60  9       13      1340
668.20  9       14      1333
631.80  8       14      1326
598.00  7       13      1320
559.00  8       15      1315
520.00  7       15      1309
483.60  6       14      1304
449.80  5       13      1300
410.80  6       15      1297
371.80  5       15      1293
332.80  4       15      1290
293.80  4       15      1288
257.40  3       14      1286
228.80  2       11      1285
189.80  2       15      1285
153.40  2       14      1285
117.00  1       14      1285
80.60   1       14      1286
39.00   0       16      1287
0.00    0       15      1289
-36.40  0       14      1291
-65.00  0       11      1293
-104.00 -1      15      1295
-143.00 -2      15      1298
-182.00 -2      15      1302
-218.40 -3      14      1306
-252.20 -3      13      1311
-288.60 -4      14      1316
-325.00 -4      14      1322
-361.40 -5      14      1328
-403.00 -6      16      1335
-442.00 -6      15      1343
-478.40 -6      14      1351
-517.40 -7      15      1359
-551.20 -7      13      1368
-590.20 -8      15      1377
-629.20 -9      15      1387
-665.60 -9      14      1398
-694.20 -7      11      1409
-746.20 -14     20      1418
-782.60 -10     14      1434
-821.60 -12     15      1446
-860.60 -12     15      1460
-899.60 -13     15      1474
-938.60 -14     15      1489
-980.20 -15     16      1505

```

# Answer
> 4 votes
When calculating the change in y-position, you aren't accounting for the change in velocity between frames. Essentially what you have is this:

```
s = change in position
v = velocity
t = time between frames
a = acceleration

v += a * t
s = v * t

```

What you should have is this:

```
s = change in position
v = velocity
t = time between frames
a = acceleration

s = v * t + 0.5 * a * t * t
v += a * t

```

Here's a video explaining the above formula.

Alternatively, here's some text to read.

Since we're talking about video games, though, an easy solution is to implement a fixed timestep.

---
Tags: jumping
---


title: Blender-to-Unity Animation Issue

text:
# Question
Title: Blender-to-Unity Animation Issue
I've been programming games for quite a few years now, but I recently thought I would try my hand at some simple 3D modeling and animation. I'm currently using Unity and Blender. In Blender, I was able to make a model and animate it using bones without too many issues. I created an extremely simple walking animation for my basic character I modeled. However, when I import it into Unity, the left leg always does a weird rotation around its Y axis halfway through the animation. All the other parts work just fine. I messed with it forever trying to fix it. Eventually, I created a whole new skeleton from scratch, and it's still doing the exact same thing. I've exported it in every format that Blender/Unity support and the issue persists. I've included some screenshots below to better describe my issue.

The animation starts out fine. All I'm doing here is rotating the left leg up and back down.

We've moved up a little further. Still going good.

Right about halfway up, the leg spins quickly once around its Y axis.

It spins all the way around and stops back where it's supposed to be in about half a second.

Then it continues on normally until it reaches the top. One the way back down, it does the exact same thing at the exact same spot, just in reverse.

My animation in Blender plays perfectly and is very simple. It's just a rotation on a single axis over 60 frames. The screenshots are from my most recent attempt (I've done this animation at least a dozen times now.) So all I did was just try animating the left leg and nothing else.

This never happens with any other bones. The right leg animates perfectly, the arms animate just fine, etc.

Any help would be greatly appreciated. Like I said, I'm very new to all of this. This is my first attempt at modeling and animating. I apologize if I missed something obvious. I've been Googling for an answer to this issue for two days now.

# Answer
I figured out how to fix this, but I'm still not entirely positive what the actual problem was. My rotation was very simple and was only in the X axis. The Y and Z axis remained at 0 throughout the rotation. However, if I manually type 0 into these boxes (even though they are already 0) the weird rotation problem goes away. This is repeatable. If I don't manually type 0 into the Y and Z axis of the rotation in the animation, it will do the weird rotation in Unity. If I do type 0 into the Y and Z axis, the animation plays perfectly in Unity. I confirmed this several times and it works, but I'm not sure why.

So, I solved the problem, I'm just not sure what was actually causing the problem in the first place.
> 2 votes

# Answer
Are your keyframes in all 3 rotation channels? Try Ctrl+N in edit mode for the bones. Good luck.

EDIT:

are your rotations set to global or local? when you press i to enter a keyframe are you selecting locRot or Rotation?

Whichever one you are using, try the other one.
> -1 votes

---
Tags: unity, animation, blender, skeletal-animation
---


# Question
Title: What's the best way to save scores per level in android?
I'm in the middle of programming a tile based puzzle game, then i realized i don't have any good ways to save data. For the moment i'm using these long combined strings for sharedpreferences and i'm very sure SharedPreferences isn't designed to keep all my per level scores.

I've got 63 levels, spread into 7 difficulties, and all scores(stars granted) is saved like this:

```
prefs.edit().putInt("achievedstars"+current_difficulty+"_"+current_level, stars_granted).commit();

```

This means i am saving 63 of those strings as for only the stars granted for the levels. I also want to save "best amount of moves", "time used", and possibly more.

The game is not going to have a leaderboard, or communicate with others devices (although it may allow posting scores to FaceBook, twitter etc.)

Another thing that might be useful to mention is that the file should not be accessible(or atleast not readable enough for people to cheat)

What would you suggest as the best way of saving stats like this from android applications?

# Answer
You have multiple choices:

**Shared preferences file** is the one you are now using. It's usable and nice key-value store, but should be used only for settings type data. Maybe for username, time played, etc. Nothing too complicated.

**Saving files in Android's file system** is better choice for your problem. How ever, you wanted to secure the file, so that user can't modify it.

**Using databases managed by SQLite** is bit heavy solution for this kind of stuff, but once setup, is easy to use and harder for everyday cheaters get theirs hands on the data. However, i think this is bit overkill for that kind of data.

---

You could use file system to store XML data or plain text with some format you can figure out yourself. You could for example, store line by line, so that first is key and next line is value or you could write key and value same line, with some separator, like "|". It's really up to you.

If you go with file system and you are only worried that if user manually locates the file and then edits it, you could do few things that give some security for the file.

First, base64 encode the file data. This makes reading and writing file by hand a tedious job. Notice, this is quite standard so user with knowledge and will, can still find out what's going on with your file. However, this works for most of users.

```
// Make unreadable
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Make readable again
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");

```

Second, hash your file and store that hash to userprefs. When you load the file data, hash it and compare to the hash stored in userprefs. If they are not equal, user has changed something from it. Check this SO answer for how to hash data with SHA1. https://stackoverflow.com/questions/5980658/how-to-sha1-hash-a-string-in-android

Please notice, while these add "security", it's not cheat proof still, but it's a start.
> 1 votes

---
Tags: android, savegame, statistics
---


# Question
Title: In JBox2D, where is the correct place to interact with Body objects? step() method?
QUESTION: In an application, where is the appropriate place to put the code to interact with the Body objects?

By 'interact' I mean

1. Get position
2. Determine actions
3. Apply impulse

Would it be appropriate to use the step() method to process the interactions?

I'm guessing responding to collisions would be done in the listeners.

**Background:**
Disclosure: I'm very new to JBox2D, and haven't used Box2D at all.
I'm using the Testbed JAR in my application so that I can see the Bodies interact.
The Body objects are controlled by simple AI, not user input.
I skimmed through the box2d v2.3.0 user manual to get a basic understanding of the objects in the world.
I didn't find any hints on where to put the decision logic.

# Answer
You're on the right track.

The `step()` method *is* the right place to put game decision logic.

JBox2D's tests directory contains great reference examples. Among them is `ApplyForce.java`, which is similar to your description. It applies forces to a body based on decision logic—inside `step()`. Their decisions are based on keyboard inputs, but you could easily replace them with AI.

Because JBox2D follows the API of the original C++ Box2D closely, the original Box2D's manual is helpful.

There's already a question on contact listeners in JBox2D with a good answer that explains how they work. There's also a `CollisionProcessing.java`-test, but note that the technicalities of the collision-listening happen in its superclass, `TestbedTest.java`.
> 0 votes

---
Tags: box2d, jbox2d
---


title: Daily Unlock in LibGDX

text:
# Question
Title: Daily Unlock in LibGDX
I am trying to make a game that is a collection of mini games. The mini games will unlock daily. There are story for each day. And the story cannot be repeated so for example the player start playing the game on Monday. He/she will unlock the story for day one and the first mini game. To unlock the next story he/she must wait until the next day. If the player skip playing at Tuesday and resume at Wednesday then he/she will lose the second story and the second mini game. My question is how to get current time that is not taken from android settings to prevent cheating? I want to prevent the player from cheating by changing android time from settings.

# Answer
> My question is how to get current time that is not taken from android settings to prevent cheating? I want to prevent the player from cheating by changing android time from settings.

I see only one workaround, get a timestamp from the internet. Here for example : **http://currentmillis.com/api/millis-since-unix-epoch.php**

Of course that would force your players to turn-on mobile data or wi-fi, what would be only meaningful for an online game. Blocking the access to the game if there is no internet available would solve the cheating problem then, but will eventually frustrate players if it supposed to be offline play.
> 1 votes

---
Tags: java, libgdx
---


title: Rotating a view of a chunked 2d tilemap

text:
# Question
Title: Rotating a view of a chunked 2d tilemap
I'm working on a top-down (oblique) tile-based engine. I would like for the tiles to have a definable height in the world, with Characters being occluded by them, etc.

This has led to a desire to be able to "rotate" the view of the world, even though I'm using all hand-drawn graphics and blitting.

Therefor, I need to rotate the actual world itself, or change how the Camera traverses these arrays.

**How can, or should, I create individual rotations of 90 degrees, when I have multi-dimensional arrays?**

Is it faster to actually rotate the array, to access it differently, or to create pre-computed *accessor*(?) arrays, something like how my chunks work?

**How can I rotate an individual chunk, or set of chunks?**

Currently I establish my tile grid like this (tile height not included):

```
function Surface(WIDTH, HEIGHT)
{
  WIDTH = Math.max(WIDTH-(WIDTH%TPC), TPC);
  HEIGHT = Math.max(HEIGHT-(HEIGHT%TPC), TPC);

  this.tiles = [];
  this.chunks = [];

  //Establish tiles
  for(var x = 0; x < WIDTH; x++)
  {
    var col = [],
        ch_x = Math.floor(x/TPC);

    if(!this.chunks[ch_x])
      this.chunks.push([]);

    for(var y = 0; y < HEIGHT; y++)
    {
      var tile = new Tile(x, y),
          ch_y = Math.floor(y/TPC);

      if(!this.chunks[ch_x][ch_y])
        this.chunks[ch_x].push([]);

      this.chunks[ch_x][ch_y].push(tile);

      col.push(tile);
    }

    this.tiles.push(col);
  }
};

```

Even some basic advice on my data struct would be much appreciated.

# Answer
> 0 votes
I don't think speed is a huge issue between your different methods so you might go with whichever approach you think is easiest. I would absolutely choose to access the arrays differently and not store pre-rotated versions of them.

For rotating one chunk: normal rotation gives you array\[x\]\[y\] -90 degrees would give you array\[WIDTH-1-y\]\[x\] 180 degrees would give you array\[WIDTH-1-x\]\[HEIGHT-1-y\] 90 degrees would give you array\[y\]\[HEIGHT-1-x\]

I would recommend somehow putting chunk access behind a layer of abstraction. Just ask for tiles on the map relative to the player and change access to the tiles based on the rotation.

As for improving your question, I don't think that's anything anyone can answer. You'd have to consider what motivates people to answer questions. Personally, I almost didn't answer because the question seems too simple and I don't know enough to understand what is giving you trouble so I don't feel that I can help.

---
Tags: javascript, camera, tiles
---


# Question
Title: How do I avoid removal from Play Store due to copyright infringement?
I made a simple Batman puzzle game using some Batman posters from the internet. There are apps on Google Play Store and Windows Phone Store that also feature these kind of Batman pictures, but they haven't been removed. My app was removed from the Play Store because of this copyright thing.

How do I publish my app to stores without copyright issues?

# Answer
> 15 votes
> There are apps on Google Play Store and Windows Phone Store that also feature these kind of Batman pictures.

You probably just had less luck than them, or intended to make profit on your app. By what you stated, you also used "posters" which are pictures that can be easily spotted by a bot.

I know that will not be helpful, but if you don't want your app to be removed from the store for such reason, you have two choices:

* **Don't use copyrighted content or characters**
* **Contact the right holders to buy a license on their copyrighted content.**

By commiting such copyright infrigments, you risk serious trials or even worse, to get a lifetime ban for your developer account. Be careful!

---
Tags: copyright
---


# Question
Title: Implementing directional lighting in voxel based polygon-engine
I'm having trouble implementing directional lighting. (I'm not that familiar with 3D.)

The problem is that the lighting does not "follow/flow with" the other blocks next to them.

How should I fix this.

At the moment all vertices have there own normals.

Should I combine or re-position normals if the blocks are next to each other?

(I tried combining the normals but then it just looks like a plain, as if its just one color.)

Should I maybe do that kind of behaviour with shadows and is directional lighting specifically for ambient lighting and not so much for diffused lighting?

This is a little bit of the code that contains the normals (the last 3 values).

```
        {0, {x * BLOCK_RENDER_SIZE                    , y * BLOCK_RENDER_SIZE                    , z * BLOCK_RENDER_SIZE                    , getBlockColor(), -1.0f, -1.0f, -1.0f}},
        {1, {x * BLOCK_RENDER_SIZE                    , y * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, z * BLOCK_RENDER_SIZE                    , getBlockColor(), -1.0f,  1.0f,  1.0f}},

        {2, {x * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, y * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, z * BLOCK_RENDER_SIZE                    , getBlockColor(),  1.0f,  1.0f, -1.0f}},
        {3, {x * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, y * BLOCK_RENDER_SIZE                    , z * BLOCK_RENDER_SIZE                    , getBlockColor(),  1.0f, -1.0f, -1.0f}},

        {4, {x * BLOCK_RENDER_SIZE                    , y * BLOCK_RENDER_SIZE                    , z * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, getBlockColor(), -1.0f, -1.0f,  1.0f}},
        {5, {x * BLOCK_RENDER_SIZE                    , y * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, z * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, getBlockColor(), -1.0f,  1.0f,  1.0f}},

        {6, {x * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, y * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, z * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, getBlockColor(),  1.0f,  1.0f,  1.0f}},
        {7, {x * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, y * BLOCK_RENDER_SIZE                    , z * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE, getBlockColor(),  1.0f, -1.0f,  1.0f}}

```

(I didn't add more code because I don't think its necessary)

# Answer
If you would do hard normals for these boxes it would eliminate your problem. For that you have to have a normal not per vertex, but per face.
You could do this by having four vertices with the same normal for each face of the cube, that is 24 vertices. That way, a whole face will receive an even amount of light.
You also mention that you tried to combine normals somehow and got a result where it seems as if it were a plain. It should be the correct behaviour, you can add more immersion to your scene by shadowing it and doing ambient occlusion.
> 0 votes

# Answer
Before you get too deep into this project I'd like to comment. It looks like you're drawing the whole cube for each block in the world. If I am wrong, then ignore this, but if I'm right you should definitely consider a more efficient approach. You do want one normal per face, which probably means drawing cubes with 24 vertices (4 vertices per face, instead of sharing vertices), but you should also make sure not to draw faces that are next to a solid block. That way you aren't drawing a bunch of polygons underground that never get seen.
> 0 votes

---
Tags: c++, shaders, directx11, lighting
---


# Question
Title: Fit a bounding box in the scene modifying FOV
Suppose I have a radius for a spherical bounding box around a mesh.

My goal is to render the scene such as when the camera moves, the bounding box whose centre the camera look at, occupies always more or less the same space. To do so I'm changing the FOV of the camera when it moves, in particular I do:

`FOV = 2 * arctan(radius/distance)`

which is the value I feed to  `glm::perspective`  after the conversion to degrees.

whereas the distance is obtained by

`distance = glm::distance(BBCentre, cameraPosition)`

The problem is that when the distance becomes small it is like zooming out the object. For bigger distances, although the object does not occupy the portion of screen I was expecting, it doesn't move.

Am I doing something wrong here?

# Answer
I believe I know why it's behaving strangely.

Here's a diagram I drew conceptually demonstrating the problem:

I would solve the math for you too, but it should be easy enough from here. Give it a try and if you get stuck, just comment and ask.
> 1 votes

---
Tags: mathematics, camera, perspective
---


# Question
Title: What alternatives are there for creating Keyboard/Mouse controls in LWJGL?
So I'm currently working my way through openGL tutorials, using LWJGL to do all my work in. However as I get to the part on how to access Keyboard and Mouse events in this library, I stumble across this little gem:

**public static void poll()**

*Polls the keyboard for its current state. Access the polled values using the isKeyDown method. By using this method, it is possible to "miss" keyboard keys if you don't poll fast enough...* (from http://www.lwjgl.org/javadoc/org/lwjgl/input/Keyboard.html#poll())

So in order to make use of Buffered Input (as the top answer in LWJGL multiple keyboard/mouse input checks calls it) you have to use this poll() method.

This means that no matter what I do, I will miss key presses if I use LWJGL for this. I have made a test with this bit of code:

```
while(Keyboard.next()) {
    int character = Keyboard.getEventCharacter();
    int key = Keyboard.getEventKey();
    String charName= Keyboard.getKeyName(key);
    System.out.println(charName+""+character);
}

```

When pressing the buttons Z X C V at the same time, an example output is as follows: Z122 V118 X120 C0 V0 Z0

As you can see the C press and X release aren't found in the buffer. In some cases a single keystroke had both the press and release missing from the buffer.

I need this to not be the case and polling faster doesn't solve the issue at all (why would that even be a solution?). So what are the alternatives for this system?

(P.S. Yes pressing those 4 buttons at the same time was properly recorded in other applications)

# Answer
I'd like to help but your code is working fine for me.

```
public static void main(String[] args) throws Exception {

  DisplayMode displayMode = new DisplayMode(640, 480);
  Display.setDisplayMode(displayMode);
  Display.setTitle("Input test");
  Display.create();

  System.out.println("OpenGL version: " + GL11.glGetString(GL11.GL_VERSION));

  while(!Display.isCloseRequested()) {
    while(Keyboard.next()) {
        int character = Keyboard.getEventCharacter();
        int key = Keyboard.getEventKey();
        String charName= Keyboard.getKeyName(key);
        System.out.println(charName+""+character);
    }
    Display.sync(60);
    Display.update();
  }

  Display.destroy();
}

```

Are you running at a fair framerate and calling Input.poll()? Input.poll() is included in Display.update() but Display.update() does a bit more than that so it might be the culprit. I have experienced window lag and other failures when the display is not being updated. As far as I know Input.poll() gets all input changes since the last call to Input.poll(). If I understand correctly the computer's hardware has a rather large input buffer as well. Missing keys just shouldn't happen.
> 1 votes

---
Tags: java, lwjgl, keyboard, control, polling
---


title: OpenGL +SFML + GLFW3

text:
# Question
Title: OpenGL +SFML + GLFW3
I'am maybe asking a stupid question, but can we mix OpenGl + SMFL and add to it some GLFW in the same SFML window ?

# Answer
Here is a link on how mix openGL code with the SFML, are you sure that the GLFW feature that you are looking for, aren't on the sfml already, because in my experience there is no reasone for mix up this two library.
> 2 votes

---
Tags: opengl, sfml, glfw
---


title: How does Texture Mapping work?

text:
# Question
Title: How does Texture Mapping work?
I read the answers from What exactly is UV and UVW Mapping? and How does UVW texture mapping work?, which are quite nice, but am still not 100% sure, if I understand correctly.

Lets start with a 2D example. So, say I have a triangle (obviously described by 3 vertices). Now my question is, how do I convert a (x,y)-coordinate to the (u,v)-coordinate of my texture? Since {x,y} could be any value between \[0,n\] with n being all real numbers, considering that it is in object space. But my texture coordinates are between \[0,1\]. How do I know how to map lets say (3,4) to (u,v)? If I know how to map the object coordinates to the texture coordinate it is easy to interpolate the values, I assume (either using bilinear interpolation or barycentric interpolation).

And then how would this work for 3D? Lets say in this case we would have a pyramide with 5 vertices (4 bottom, 1 tip). I guess the procedure would be similar, with the exception that I know have an additional depth value. But how does the mapping of a 2D texture work on a 3D object, when I don't have nice flat surfaces like on a pyramide, but instead have a circular surface, like a tea pot?

I hope I'm clear in my questions. I'm still little confused myself. I just don't quite get the mathematical background of texture mapping.

It would be enough, if you could point me to some website with good explanation, maybe with clear graphics and step by step description.

Thanks for your time!

# Answer
> 1 votes
> How do I know how to map lets say (3,4) to (u,v)?

First of all, your assumption is wrong. You don't transform position coordinates to uv coordinates, your vertice already has a uv coordinate. Like the following:

Where (100,125) is the position of the first vertex (in pixels) and (0,0) is the UV coordinate. Mapping that point to the texture is a simply finding which pixel in the texture is the pixel (0,0). This is usually done for you in the shader when you use texture lookup functions. Finding the uv coordinate of any point in the triangle is done by using the 3 uv coordinates and finding out the average in that specific point.

The same happens when you have a 3D object, you will map your vertices to a 2D uv map (usually done by whoever is makes the model) and then use the UV coordinates for the 2D lookup.

# Answer
> 0 votes
Each of the vertexes of the triangle will have a `u,v` coordinate assigned. When the triangle is projected onto the screen each point that is displayed on screen will have a set of barycentric coordinates.

Then to get the texture coordinate you just take the average of the texture coordinates weighted by the barycentric coordinates.

In openGL this is done automatically when you select varying as output of the vertex shader and input of the fragment shader.

---
Tags: textures, uv-mapping
---


title: How can I skew my XNA sprites?

text:
# Question
Title: How can I skew my XNA sprites?
I would like to make a 2D tile based game, but, to make it look a bit prettier, I would need to skew textures so that it would look more like a 2.5D game. So I thought maybe I should skew textures to something like this:

So far I only found one topic about it - http://forums.create.msdn.com/forums/p/37143/215098.aspx#215098

But I don't really understand it. Maybe some of you do, can tell me how to skew my sprites?

# Answer
> 2 votes
If you use a textured quad, you have some additional flexibility over the geometry that you wouldn't have with a `SpriteBatch`. This will allow you to implement the skewing you're after. You can then implement the skew:

* Pinch the top two vertices in on the X axis (or push the bottom two vertices out along the same axis). That is, create a quad with corner points at, say, (-0.5, 1.0f), (0.5, 1.0), (1.0, -1.0), (-1.0, -1.0). This is the approach you'd have to take if you are using an orthographic projection elsewhere.
* Push the top two vertices away from the camera along the Z axis (give them Z coordinates of, say, 0.5 if the rest of your quad is in the Z = 0.0 plane). If you use a perspective projection, this will achieve the skew naturally.

Both options will potentially have slightly different results in terms of the appearance of the texture mapped to the quad, and both approaches are more appropriate for certain kinds of existing rendering pipelines (primarily based around the projection matrix you are currently using). You'll have to pick the one that best fits your code and your desired visual style.

Note that abandoning `SpriteBatch` means you lose some of the batching optimizations it makes for you, which you may need to re-implement depending on the overall performance (and performance bar) of your game.

(Also note that a third option would be to just author the sprite textures with the desired perspective distortion built-in, which means you can simply continue to use `SpriteBatch`, but adjusting the perspective would be difficult as it would require re-authoring your sprites.)

---
Tags: xna, 2d
---


title: Love2D Box2D RevoluteJoint and Anchors

text:
# Question
Title: Love2D Box2D RevoluteJoint and Anchors
and apologies in advance for this fairly random question.

I'm using Love2D 0.9.1 and Box2D to create two bodies joined by a revolute joint. A simplified representation of the two bodies is a Sphere and a rectangle:

```
hero.heroPhysics = {}
hero.heroPhysics.body = love.physics.newBody(theWorld, hero.x,hero.y,"dynamic")
hero.heroPhysics.shape = love.physics.newCircleShape(CONSTANT_heroRadius)

hero.extraPhysics = {}
hero.extraPhysics.body = love.physics.newBody(theWorld, hero.x,hero.y,"dynamic")
hero.extraPhysics.shape = love.physics.newRectangleShape(CONSTANT_heroRadius * 3, 8)

hero.jointPhysics = {}
local hx,hy = hero.heroPhysics.body:getWorldCenter()
hero.jointPhysics.joint = love.physics.newRevoluteJoint(hero.heroPhysics.body, hero.extraPhysics.body, hx, hy, false)

```

Everything seems to be ok, except that the anchor points of the joint are the centers of mass of the two bodies, and I'd like to manually adjust the anchor point of the rectangle to be closer to one end of the rectangle. However, I can't find a way in Love2D to set the joint anchor points? I can get the anchor points via Joint:getAnchors(), but not set them? Or maybe I'm missing something.

In pictures, I'm only able to get something resembling the bottom picture, whereas I really want something like the top picture (please excuse crude drawing):

I've tried changing the rectangle body's center of mass using body:setMassData(), but that doesn't seem to make a difference (unless I try to offset it too much, at which point Box2D dies).

# Answer
The method of controlling the anchor points on both of the bodies doesn't seem straightforward at first, but if you think about it in the following manner, it makes sense.

Consider two pieces of construction paper such as the rectangle and circle in your example. I can translate and rotate these two pieces anywhere I want on a flat surface. They are allowed to overlap. If I want to join them together at a point while allowing them to rotate relative to one another, I would position them in an appropriate starting position and then insert a split push pin at the rotation point (i.e. the pink dot on your drawings).

Split push pin:

This is how the anchor points are specified in box2d. Like pieces of construction paper, you should first position the bodies appropriately and then create the revolute joint. The only line in your example that needs to change is where you create the other physics body:

```
hero.extraPhysics.body = love.physics.newBody(theWorld, hero.x + CONSTANT_heroRadius*(3/8), hero.y,"dynamic")

```

This will position the center of the `extraPhysics.body` 3/8 of the `CONSTANT_heroRadius` to the right, so that when the revolute joint is created, the desired local anchor points will be set on each body.
> 1 votes

---
Tags: box2d, love2d
---


# Question
Title: what happens with missing vertices in geometry shader
I am relatively new to GLSL shader programming, and the documentation I found is unfortunately often inscrutable. I am having trouble understanding a few things with how geometry shaders fit into the pipeline.

I am trying to implement silhouette detection by detecting boundary triangles in a geometry shader. A triangle is a boundary triangle if it is front-facing and an adjacent triangle is back facing. The idea then is to emit additional camera-facing triangles to outline them.

For this purpose, I am looking at `GL_TRIANGLE_ADJACENCY` shaders, since they seem to fit the bill. Let's assume for the moment that I have already got the data loaded properly into the buffer.

For clarity: I plan on doing skinning and the Model View transform in the vertex shader, but to hold off on the perspective projection until I decide what to do in the geometry shader (this seems reasonable, but maybe I am wrong).

Here is where the uncertainties start to come in. First of all, am I expected to manually perform backface culling at some shader stage?

Second, if a triangle has incomplete adjacency information(only 2 out of three triangles for example), how is this conveyed to the shader? Does it just have a length less than 6 vertices?

Third, what does the pass through shader (the one that does nothing special) have to perform? Do I emit every vertex in the input list, or just 3 from the first triangle? And again, am I supposed to/allowed to cull backfaces?

And last, if I decide to emit additional geometry, is there anyway to distinguish that from the (passed-through) input geometry from the point of view of the fragment shader? I'd like to be able to texture map them separately if it is possible.

If I am on the wrong path on any of this, of course feel free to let me know. In case it is important, I am using OpenGL 3.3.

Based on my understanding and Nathan's answer, I could start with a passthrough shader that looks something like this:

```
layout(triangle_adjacency) in;
layout(triangle_strip, max_vertices = 14) out;
flat out float is_border;

void main() {
    gl_Position = gl_in[0].gl_Position;
    is_border=0.0;
    EmitVertex();

    gl_Position = gl_in[2].gl_Position;
    is_border=0.0;
    EmitVertex();

    gl_Position = gl_in[4].gl_Position;
    is_border=0.0;
    EmitVertex();

    EndPrimitive();
}

```

And then when/if I add triangle strips for outlines, I will set `is_border=1.0` for each of those vertices.

# Answer
> 3 votes
You don't need to perform backface culling manually in the geometry shader. (It's possible it could be an optimization to do so, if culling allows you to skip some expensive work in the rest of the geometry shader. But that seems unlikely to be the case.)

Triangles can't have incomplete adjacency information. The vertex buffer for `GL_TRIANGLE_ADJACENCY` always has exactly 6 vertices for each triangle; there is no way to specify a triangle with only part of that information.

The passthrough shader would only need to emit the three vertices in the triangle being processed; it doesn't need to emit any adjacency information since this is not used anyway by the rasterization and fragment processing stages.

You can emit additional vertex attributes from the geometry shader (beyond the ones passed through from the vertex shader), so you can add some attribute to tell the fragment shader which triangles are originals, versus new ones - just set the attribute appropriately when you emit them from the geometry shader.

BTW, holding off on the view and/or projection transform until the geometry shader (thus outputting in world space or view space from the vertex shader) is perfectly OK and a common thing to do.

---
Tags: opengl, glsl, geometry-shader
---


# Question
Title: How do you create a 2d world then view it in 3d?
I have been learning OpenGL for a while now and have a pretty good understanding so far.

What I would like to know is if I create a 2D game in Orthographic Projection, is it possible to switch to a perspective projection and view the scene without having to manually adjust the camera etc?

Thanks

# Answer
It really depends on the geometry that your world consists of and how you set your orthographic projection and camera up relative to that world.

Most of the time, when people make 2D games with orthographic projections, they don't bother actually creating 3D geometry. Usually everything is a quad with a texture applied, or simple 3D geometry without much actual "depth" (since the projection renders that depth relatively useless). Thus, switching to a 3D view with perspective would result in a flat or oddly-spaced world with a lot of Paper Mario-style thin objects.

Similarly, orthographic projection parameters are usually set up to map world units to pixels, or similar. It's *possible* to simply substitute a orthographic projection with a perspective one, but unless you've done a lot of careful pre-planning with the camera parameters and field-of-view, et cetera, you're likely to get a image of the world that is too "zoomed in" or too "zoomed out" and thus you'd want to make at least some *minor* adjustments to the camera in the perspective mode to account for this.

Without more information about the background behind your question (what is the overall problem you are trying to solve), the answer is basically that "it depends." It's potentially doable in general, but whether it will work in practice for your project is hard to say.
> 2 votes

---
Tags: opengl, 2d, 3d, projection
---


# Question
Title: How should I implement the "Observer" pattern with respect to a game world?
I'm thinking of ways to implement the Observer pattern in a game I'm developing at the moment. I can have a Game World (local map) with Game Objects (player, NPCs, monsters etc...) inside of it. Other Game classes (like quest progression tracker for flagging triggers, location tracker for path finding, or maybe a new map need to be loaded into memory and rendered to show the new area the player just walked into) need to be notified when the player walks into a building, or fires a projectile. Also the input listener needs to be aware of when the user presses a key or clicks the mouse, and somehow transport that information to the rest of the game so that it can allow the appropriate actions to take place.

So I'm stuck at the implementation stage. I know I can use the Observer pattern, and possibly the State pattern as well. I know I'll need a Game World (Subject), Game Objects (Listeners), and Game Events (triggers the Game World to render the changes). However that could be the wrong way to go about it, any suggestions?

BTW, its a 2D JRPG tiling styled game, in the fashion of Zelda, Breadth of Fire, Pokémon, or the older Final Fantasies

Alright I've gone and done an implementation, but ran into a few minor issues, although it seems to be working properly.

```
public interface WorldListener {
    public void OnWorldEvent(WorldEvent e);
}

```

Above is the Observer that listens to the subject.

```
public class WorldEvent {
    final int WorldObjectMovedEvent = 1;
}

```

Above is the Event that triggers a notification.

```
public class World {

    static WorldListener listener;

    static void addWorldListener(WorldListener wl) {
        listener = wl;
    }

    static void WorldChanged() {
        listener.OnWorldEvent(new WorldEvent());
    }
}

```

Above is the subject that only stores one subscriber at the moment, I'll make it into a list once i write a class for another observer, right now, I only have one Observer. There is no need for a list at the moment.

```
public void OnWorldEvent(WorldEvent e) {
    System.out.println("Something has happened in the world");
}

static private void addWorldListener(WorldListener wl) {
    World.addWorldListener(wl);
}

```

The code above goes into the object that is currently acting as an observer, when an event is fired, it triggers the world's `WorldChanged()` method, which in turn fires the `OnWorldEvent` of any listener.

The problem I have ran into is that I can't move the `WorldEvent`, `WorldListener`, or `World` classes into a separate package under the moniker `World.my.game` because of the static reference. So I'm not sure I'm implementing it correctly. Also if there are any suggestions on making this better, or if I'm flat out doing it wrong let me know, as I haven't delved into design patterns yet and this is my first attempt.

# Answer
> The problems i have run into is i can't move the WorldEvent,WorldListener, or World classes into a separate package under the moniker World.my.game because of the static reference.

Don't make the listener inside the `World` object static. A static class member means the object is shared across all instances of the type (all instances of `World` in this case). That's not want you want here: you want each `World` to have it's *own* listener, so client code can listen to the individual world or worlds it cares about.

> i haven't delved into design patterns yet and this is my first attempt

This is a problem that most people have when first hearing about or approaching "design patterns." Design patterns exist to create a common vocabulary for talking about problems and solutions. They should not be viewed as solutions *in and of themselves*. That means when you encounter a problem, you shouldn't necessarily go hunting for a "design pattern" to try and fit over the problem, and you shouldn't worry about implementing the solution to a problem "correctly" in terms of the canonical definition of the pattern.

Focus instead on solving the actual problem. In this case, the problem you have encountered is that you need some way for other code to react to world events when they happen. And it's true that this the basic premise of the observer pattern -- but that doesn't mean there is a single "correct" way to implement the observer (and there shouldn't be!), nor does it mean you should think about the solution in terms of the pattern. It is a subtle distinction, but it will help you avoid "square peg, round hole" problems in the future if you focus more on the needs of the solution rather than the definition of the pattern.
> 2 votes

---
Tags: java, game-design, architecture, design-patterns
---


# Question
Title: Collision detection: Swinging bat/racket and ball
I am programming a side-view tennis game, inspired by an old arcade game, using Javscript and HTML5 canvas elements. The player can move left and right and holds a racket at arms length which can be rotated 360 degrees around the shoulder joint.

I am quite happy with the collision detection and resulting deflection angle between the racket and the ball in the case where the player stands still and the racket does not move. I use a ray-casting approach for this collision detection between the vector that represents the racket and the trajectory vector for the ball as proposed here.

However, I am having trouble implementing the collision detection between the rotating racket and the ball. When the racket is swung, the area in which a collision would apply has a shape similar to a circular segment , but the racket rotates rotates to fast and the collision detection does not pick it up in most cases. The image bellow illustrates the problem, the red arrow indicates the direction of the swinging racket.

The following code snippet from the player entity's update function shows how the racket is updated. `arcmx` and `armcy` is the location of the shoulder joint, `rstart_` and `rend_` are the beginning and end of the racket.

```
  if(KEY_STATUS.rleft || KEY_STATUS.rright) {
    if(KEY_STATUS.rright) {
      this.rangle += this.rspeed;
    } else if (KEY_STATUS.rleft) {
      this.rangle -= this.rspeed;
    }
  }

  this.armcx = this.x + this.width/2;
  this.armcy = this.y + 46;
  this.rstartx = this.armcx + Math.cos(this.rangle)*40;
  this.rstarty = this.armcy + Math.sin(this.rangle)*40;

  this.rendx = this.armcx + Math.cos(this.rangle)*71;
  this.rendy = this.armcy + Math.sin(this.rangle)*71;

```

I am pretty lost on this problem and appreciate any hints on how to approach it.

# Answer
> 1 votes
Multisampling, as the people over at Metanet call it.

Basically, you do a racket/ball collision test at frequent enough time intervals between frames such that the ball can't be passed by the racket without a collision being detected. This gives a rough estimate as to when the collision occurred, after which you can start subdividing your time step to find the exact moment of contact (the more accurate you want it, the more you subdivide). This should ensure collisions are correctly detected, and consistent.

Or perform a sweep test (arguably harder to implement).

# Answer
> 0 votes
What you could do is give the racket a defined constant "range" that is +- half the distance the ball moves every update. This way the ball would never pass through the racket. This will of course result in minor inconsistencies with the ball's rebound trajectory, but you'd have to test this out to determine their actual effects.

Yes the logical size of the racket would then change dynamically, but that is the best way that I can think of to correctly determine when the ball *would* hit the racket, without impeding onto the performance too badly.

**Although you could move the ball and racket minute distances multiple times per update and then check after each movement.** This seems a little tedious and could possibly be a little tough on the hardware depending the system running the game, but it would probably be most accurate.

I have done this for a game of my own where I had to check whether a balloon touched the top of the spike, rather than the sides, so this is a valid method, although it could possibly be fine-tuned a bit to fit your game.

---
Tags: collision-detection, javascript, vector
---


# Question
Title: What method should I use to create a story game which is about making decisions?
I am planning to create a story game in VB.Net which is about making decisions and from there, there's different possible endings.

I want to know ( if there're any ) ways that can be used, other than using If Else Statements which will take a long time if that's to be used.

The game will only have texts and buttons for answers so it's really just a simple story game.

# Answer
> 1 votes
It sounds like you can implement this with a graph data structure of some sort. Each node of your graph is a story step, and each of the edges of given node are the answers which in turn lead to new story steps. In pseudocode:

```
class Node {
  string Text;
  List<Edge> Options;
}

class Edge {
  string Text;
  Node Target;
}

```

Then your game involves tracking the current node, which is initialized to the starting node of your story graph when the game loads. You display the current node's story text, and for each edge out of the current node, draw a button. When the player clicks on a button, you set the current node to node at the other end of the edge, and you repeat the process.

Nodes that have no children can be considered "end" states, and the player has reached the game (or lost, perhaps) when the current node is one such.

---
Tags: .net
---


title: Master sound volume in LibGDX

text:
# Question
Title: Master sound volume in LibGDX
I have been searching everywhere for master volume for sound and music in LibGDX but to no avail. Can anyone tell me if it is implemented somewhere or do i need to implement such functionality myself? Thanks in advance.

# Answer
> 5 votes
I'm pretty new to LibGDX but I don't think it would be too hard to implement your own version of a "master volume" - just have a float variable called master volume and then use it whenever you play your music and edit it how you please.

For example:

```
public static float mastervol = 1f;

//playing your sounds
sound1.play(mastervol);
sound2.play(mastervol);

//change your master vol
public void setMasterVolume(float i){mastervol = i;}

```

Something along those lines.

---
Tags: java, libgdx, sound, music
---


title: iOS Sprite Kit - Blend Mode Effect

text:
# Question
Title: iOS Sprite Kit - Blend Mode Effect
This question builds upon the following question: How can I achieve a good fire effect with alpha blending and particles?

I want to achieve the visual effect of using `SKBlendModeAdd` on a **black** layer, but adding it to another (random) color background.

In the question posted above, it is explained how to do this: either by using an extra texture from which the alpha layer is removed or by using *alpha premultiplication*.

I've tried implementing both, but to no avail.

This probably has to do with the following:

> A particle is a textured and colored node whose contents are blended into the **framebuffer**. Although there is no visible class representing particles added by the emitter node, you can think of a particle as having properties like any other object.

From Apple's Documentation

My guess is that because it's a `framebuffer`, the workaround solutions do not work for Sprite-Kit.

So how would I go about implementing this with `SKTexture` or `SKSpriteNode` ?

See below an example of the difference in colours between dark and light backgrounds. I would like to get the exact same colours on the light background as I get on the dark background (because on the dark background it actually looks like fire).

# Answer
> 3 votes
Wrapping the SKEmitterNode in an SKEffectNode allows the EmitterNode to be rendered into a framebuffer which is subsequently rendered onto the screen. I tested this out (after much push and pull of different nodes and scenes and views) and this results in the exact effect you want, where the Add blend mode is applied to a background that is not rendered onto the final scene, and the final scene's background is therefore not added to the values of the particles.

The only problem is that there is a dark outline to the "fire", but this is a result of the blended color being originally very dark (which is not noticeable against a dark background, but is very against a light background). This could be changed by refining the particle's color and various other properties, or accepted altogether.

Example:

```
SKEffectNode *effectNode = [[SKEffectNode alloc] init];

NSString *firePath = [[NSBundle mainBundle] pathForResource:@"Fire 3" ofType:@"sks"];
SKEmitterNode *fireEmitter = [NSKeyedUnarchiver unarchiveObjectWithFile:firePath];

fireEmitter.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));

[effectNode addChild:fireEmitter];
[self addChild:effectNode];

```

The SKEffectNode renders all descendants onto a framebuffer, so it's as simple as adding the emitter as a child to the SKEffectNode. The position is arbitrary in the example.

This isn't very efficient, and there seems to be a performance problem with little else but the fire effect. Other than editing the emitter somewhat (lowering the birthrate, etc), I imagine the best way to get this effect would be a custom shader, with the downside that it would be much more complicated and not technically "SpriteKit" mechanics.

---
Tags: ios, particles, xcode, alpha-blending, spritekit
---


# Question
Title: How do I efficiently collide and match groups of coloured circles?
I am new to game programming and working on clone of this game in libgdx.

The game has some static balls and one ball that moves. I want to check if the moving ball collides with any static ones, but I'm concerned about the performance of my method.

I could put the positions of the static balls in an array or `ArrayList` and iterate over each of them in the moving ball's `update()`-method. However, this seems too slow to me when there are more than 10 balls.

A second issue is with how to detect the colliding balls' colours to check if 3 or more with similar colors collide. How should I approach that?

# Answer
> 3 votes
For your first question you can optimize your method by only checking collisions with the border bubbles (only the bubbles that are actually exposed and not ones that are entirely surrounded). However, you can optimize this even further by using the fact that you know the coordinates of the bubble to find out approximately (or precisely, with some math) where it's going to hit. Then you can only check collisions with the bubbles in that area. Of course, this will only work if you use a sorted data structure.

A two-dimensional array will work as a sorted structure without much additional effort because it will directly correspond to the ordering in the field. However, there are other structures that you can use, albeit they might be less efficient for this scenario.

For the second question there are many possible solutions. Here's a simple one that I can think of:

Let each bubble have 3 properties: position, color, and group. Position defines the bubble's position in the array, color defines the bubble's color, and group is a reference to an ArrayList of bubbles' positions.

Each time a bubble "hits", check the colors of all bubbles around it. If a bubble with the same color is found, then add the current bubble to it's group.

There are some additional special cases to handle, but I will leave them up to you to figure out.

---
Tags: java, collision-detection, libgdx, optimization
---


# Question
Title: How to check for collisions in "diagonal" tiles?
I want to create a tiled map in the following scheme:

The player should be able to walk on the blue line (street). Now, what is the best way to solve collision detection in this case? For example, in the case of tiles C1 and C2: If I make them walkable, then the player could also move in on those black parts of the tiles that should not be walkable.

On the other hand, if I make both C1 and C2 blocked, then the player would not be able to walk on these tiles (and therefore on the street) at all.

Any best practices?
Thanks.

# Answer
Several possibilities :

1) use small `collision maps` for each different tile. It does not need to be very precise, small maps like 8x8 might be enough (depending what you need). You can do some interpolation to smooth it out.

Here is an example :

Instead of using only occupied / non-occupied state for the collision map, you might also consider using other states : half-full to bottom left, half-full top right, etc..

The blue line in example you give might be reworked a little bit to fit perfectly with that pattern.

Check this answer : How did LoZ: A Link to the Past handle sub-tile collisions?

2) do not use collision maps, but create specific code that will check for collisions : first, it finds out in which tile player is and depending that, it performs some simple math to check for collision, with code specific to each tile. It probably easy to do because most of the tiles you show have vertical, horizontal or diagonal patterns (or a combination).

Some pseudo code :

```
currentTile = //find out on which tile player is, depending position
tileType = tileMap[currentTile];

tileX = //convert player position to local position inside tile (between 0.0 and 1.0)
tileY = //

switch(tileType)
{
  case A1:
    collided = (tileY > 0.25) && (tileY < 0.75);
    break;

  case A2:
    collided = (tileX > 0.25) && (tileX < 0.75);
    break;

  case B:
    //... same as A1 but need to checks diagonally
    break;
}

```
> 2 votes

# Answer
**Treat the tilemap as purely graphical data, and use some other structure to resolve collisions.**

In your case, you can define the boundaries of your roads using edges (segments). You have a vector (line) representing the player's movement, and you want to know if this line will intersect some wall during this timestep. Since these walls are represented by edges, the problem breaks down into line-segment intersection. Pseudocode:

```
for(edge in walls) {
    intersectionPoint = intersect(movement, edge);
    relative = intersectionPoint - playerPos;

    //Ensure that we intersected a wall in the right direction,
    // and that we hit the wall on this frame
    if(sign(relative.x) == sign(movement.x) &&
       sign(relative.y) == sign(movement.y) &&
       magnitude(relative) < playerSpeed) {
        //hit wall
    }
}

```

In the above code, `intersect()` finds the point where a line and a segment intersect, `sign()` returns the sign of a scalar, and `magnitude()` returns the magnitude of a vector. The part where you intersect the movement vector with every wall can be optimized with a broad-phase approach, but doing it for every edge is often fast enough (it was for me).

The harder part with this method is figuring out how to define the edges themselves. It's kind of ungainly to have to define these edges for every level (road) you create, but it's often the easiest solution. If you already have the road data stored in some way, you could probably construct the edges from the angles and widths of the roads.

This method will also work with shapes other than straight lines. You can abstract the `intersect()` method to support, for example, arcs, and store generic shapes in the `walls` data structure.
> 0 votes

---
Tags: collision-detection, tiles, tilemap
---


# Question
Title: How to get the complete width of SKSpriteNode which has many child nodes
I have a Sprite node with many 6 child nodes. Each are placed one after another in X-axis. I want to know the complete with of the Sksprite node.

```
SKSpriteNode *array = [SKSpriteNode node];

[array addChild:box1];
[array addChild:box2];
[array addChild:box3];
[array addChild:box4];
[array addChild:box5];
[array addChild:box6];

```

array.size.width dosen't get me any size, so how should i get the complete width of array with child nodes..

If i add multiple sprites to NSMutalbleArray then how can i get the width of the complete array.

# Answer
> 5 votes
To get the complete bounding rectangle of a node and its child nodes you use the `calculateAccumulatedFrame` method. It's a member of SKNode.

I ran into this when adding my SKSpriteNodes to separate SKNodes as layers for parallax and HUD elements. I kept getting (0,0) width/height for my bounding rect on the SKNode, and I found this.

It returns a CGRect, and you can use it like so:

```
CGRect layerSize = [_layer calculateAccumulatedFrame];
float widthVar = layerSize.size.width;
//etc...

```

---
Tags: ios, xcode, spritekit
---


# Question
Title: Why is BayazitDecomposer inaccessible when upgrading from Farseer 3.3.1 to Farseer 3.5?
I used the following code in Farseer 3.3.1 and it worked correctly, but in Farseer 3.5, I always get an error message in the following line:

```
list = BayazitDecomposer.ConvexPartition(textureVertices);
'FarseerPhysics.Common.Decomposition.BayazitDecomposer' is inaccessible due to its protection level

```

What is wrong? Why is the code not working with Farseer 3.5? How can I use the decomposition tools in Farseer 3.5?

# Answer
> 1 votes
The `BayazitDecomposer` was made assembly-internal in commit 101497, which was aimed at centralizing the input validation for the triangulation algorithms in a single place according to the check-in comment:

> Removed sanity checks from all triangulators and moved them into Triangulate. Added asserts into each triangulation algorithm that checks if the polygon is valid. Triangulator is a new class that does all the work of validating inputs and sanatizing outputs.

Per that comment, one is now expected to use the `ConvexPartition` method from the `Triangulate` class, passing an enumeration value to specify the desired triangulation algorithm (as you noted, the value you want to use for a Bayazit implementation is `TriangulationAlgorithm.Bayazit`).

---

The original links will be unavaiable pending the closure of CodePlex.

Farseer Physics has been superseded by Velcro Physic and its implementation of `BayazitDecomposer` can be found here.

---
Tags: xna, c#, farseer-physics-engine
---


title: Unity's default integration method

text:
# Question
Title: Unity's default integration method
Which method(s) does Unity provide for physical integration? RK4? Verlet? Euler?

# Answer
**For 3D**, Unity uses PhysX. According to this answer, PhysX uses a symplectic integrator. The paper it cites as evidence is a bit more ambiguous though:

> Since it is a commercial engine the implementation details are unknown ... Most physics engines provide results similar to the Symplectic Euler integrator, or 2nd order Euler. Novodex (Ageia PhysX) provided the best results.

The integration error graph shows it behaving slightly better than the "Euler 2nd order" reference implementation, and significantly better than the "symplectic Euler" reference integrator. So it looks to me like it's not a 100% off-the-shelf integrator, and has some custom adjustments that may be hard to duplicate without the source code.

**For 2D**, Unity uses Box2D, which uses Symplectic Euler, according to these forum *posts (dead link)*.
> 7 votes

---
Tags: unity, physics
---


title: Mouse follow precision in flash

text:
# Question
Title: Mouse follow precision in flash
I am trying to implement a simple movement for one of game objects in flash/ AS3. I am using mouseX, mouseY for my object to follow the mouse pointer. It works fine but the problem is the precision of the movement. If I move my mouse a little too fast then my game object stops following the mouse which means I have to re-focus the mouse pointer back on the game object to make it move again.

Here is the code that does this.

```
private function FootyMouseMove(shortestFooty : FootBall) : void {
            shortestFooty.x = stage.mouseX;
            shortestFooty.y = stage.mouseY;
            if (shortestFooty.x > stage.stageWidth - shortestFooty.width)
                shortestFooty.x = stage.stageWidth - shortestFooty.width;
            if (shortestFooty.x < shortestFooty.width)
                shortestFooty.x = shortestFooty.width;
        }

```

My question is, would it be possible to make the movement of my game object much more smoother and make sure that the game object is always following the mouse no matter how fast I move my mouse pointer?

# Answer
> 1 votes
I don't think there's enough information to diagnose the problem, but my *guess* is that you have the `MOUSE_MOVE` handler on the object you're dragging. That event fires only when the mouse is over the object. When you move the mouse quickly, it ends up not over that object, so you stop getting the events. This is not a problem with “precision”, but about *where* you mouse event handlers.

If this is indeed the problem, the solution I've used in the past is to capture events on a larger sprite, such as the stage.

1. Capture `MOUSE_DOWN` on the object in question. This is the start of the drag operation.
2. In the `MOUSE_DOWN` handler, add `MOUSE_MOVE` and `MOUSE_UP` handlers to the stage object. This will let you track the movement until the mouse is released.
3. In the `MOUSE_MOVE` handler (on stage), you'll need to translate coordinates from stage to your object's coordinates using `localToGlobal` or `globalToLocal`. This is the drag operation.
4. In the `MOUSE_UP` handler (on stage), remove `MOUSE_MOVE` and `MOUSE_UP` from stage. This is the end of the drag operation.

If you want to track on mouse move even when the mouse button isn't held down, it's even simpler. Put the mouse move handler on the stage object and translate coordinates.

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


# Question
Title: Why would creating a GLFW 3 window return null?
For some reason after calling 'glfwCreateWindow' I get back `NULL` as the return value. I'm initializing GLFW beforehand with 'glfwInit' and while searching for a solution tried setting 'glfwSetErrorCallback' to print if there is an error but it doesn't call my function after returning `NULL`.

I'm using GLFW 3 with C++ on Visual Studio 2010 x64.

# Answer
> 8 votes
You can see from the source code that `glfwCreateWindow` returns a null pointer in only a few circumstances (as of this writing).

* GLFW is not initialized at all (`_GLFW_REQUIRE_INIT_OR_RETURN(NULL);` on line 137).
* The width or height you specify for the window is zero or negative.
* The context configuration (controlled by you via the window hints, checked via `_glfwIsValidContextConfig` on line 184) is invalid.
* Platform-level window creation fails (`_glfwPlatformCreateWindow` on line 216).
* Refreshing the GL context to get the actual requested context attributes fails (`_glfwRefreshContextAttribs` on line 226).
* The refreshed context doesn't match the requested context properties (`_glfwIsValidContext` on line 234).

Since you don't get an error handler callback invoked, you can probably discard the second reason (it's the only one that might fire an error handler call, and it should be pretty easy to verify on your end anyway).

This means the likely options are that you didn't initialize GLFW correctly or correctly check the return value of the initialization (you don't provide your source, so it's impossible to say) or your ask for invalid context options via the window hints system.

---
Tags: c++, glfw
---


# Question
Title: How does the GPU know how to form triangles for a given mesh?
I have just begun learning shader programing. What I learned is that the rasteriser groups three vertices to form a triangle for doing further operations. If that's true how does the rasteriser determines appropriate vertices which form a triangle in the mesh/geometry? Is it the 3D software which saves geometry in the proper order in model file like `.3ds` or `.obj`, `.x` or is it the GPU which internally triangulates the geometry irrespective of the order the vertices are passed?

# Answer
> 5 votes
You tell the GPU how to produce triangles from the input data. You specify vertex buffers containing all your vertex data, you also specify a primitive topology (lines, triangles, et cetera) and an optional index buffer.

The topology tells the GPU how many and what pattern to take the indices in (for example, in sets of three for a triangle list). The indices simply refer directly to entries in the bound vertex buffer.

If you don't specify an index buffer, the GPU takes the data from vertex buffer directly in the pattern indicated by the topology.

---

Also, strictly speaking, the GPU doesn't do *triangularization*; by the time you submit the data, it's already expected to be in triangles -- or whatever format your primitive topology demands, like lines or points. Similarly, it's not the rasterizer that handles reading the input arrangements. That's done by the GPU well in advance of the rasterization stage.

---
Tags: shaders
---


# Question
Title: Rotation with XMMatrix to Rotation with XMFLOAT3
I'm rotating a Direction Light around a fixed object, so the light only contains a XMFLOAT3 to determine it's direction that it is facing.

I have another object rotation using the variable Rotation which is an XMMATRIX.

```
Rotation = XMMatrixRotationAxis( rotaxis, rot);

```

I picked out the parts I needed by doing the following:

```
XMFLOAT3 newRotation;
newRotation.x = Rotation._11;
newRotation.y = Rotation._12;
newRotation.z = Rotation._13;

```

Is there a cleaner way of doing this? An easier built in function?

# Answer
You could do something as simple as XMVector3TransformNormal of the direction light with the original Rotation.

Generally in SIMD-friendly coding, individual component access is a performance hit, so you want to avoid doing it whenever possible. That's why in DirectXMath (aka XNAMath version 3) the individual element members \_11 - \_44 were removed from XMMATRIX. If you need to do individual matrix element access, you'd use XMStoreFloat4x4, XMStoreFloat4x3, XMStoreFloat3x3 and then extract the value from the non-SIMD structures XMFLOAT4X4 / XMFLOAT4X3 / XMFLOAT3X3.
> 1 votes

---
Tags: rotation, directx11, lighting
---


title: Splash Screen Resolution size

text:
# Question
Title: Splash Screen Resolution size
I am using LibGDX to make a very simple game. I am going to hire someone to create a splash screen logo since I'm artistically challenged. I want to order a vector graphic so I can scale it later if needed. What would be a decent size to use as a baseline (in pixels) that would scale relatively well on desktop/android/ios/etc?

# Answer
> 3 votes
Vector graphics are completely resolution-independent. Which means you can always scale them up as much as you like. There are no resolutions which scale especially well.

Vector programs like Inkscape use the px unit, but that is only the same as the output size if you output as 90 dpi. In any other case, the image will stay completely sharp, but the pixel units used inside the vector graphics program won't correspond to the pixel size outputted.

What you should care about, though, is the aspect ratio. Modern phones mostly 16:9 (landscape of portrait), while some Windows Phones have 15:9 (actually, the majority of Windows Phones). Tablets can also have other aspect ratio, mostly a bit squarer, like 16:10 or 2:3 (the Surface Pro 3). Therefore, I'd recommend you to tell the artist to fit everything inside a 16:9 aspect ratio, but put something above and below that 16:9 box so you don't have to display black bars on other aspect ratios.

---
Tags: art, scale
---


title: How do I handle this type of collision?

text:
# Question
Title: How do I handle this type of collision?
So I've been messing around with simple game development for a while and just found an interesting game idea here . I'm using SFML 2.1 with C++ and so far I have a tilemap in a VertexArray using a very similar way to this tutorial and have gotten it working with submarine movement but I feel that I have dug myself a hole with this. Here is what I have so far and you can see my simple tileset: . I am pretty lost in terms of how to handle collisions between the submarines (and anything else fired) and the walls. The only way I can really think of is pixel collision but I'm not really sure how I would implement that.

Sorry if this has been asked before but I have looked and can't find much that applies. Any help is greatly appreciated.

Thanks,

Karel

I just realised that the question is badly worded sorry. I was wondering how to do collision detection between the submarine and the walls of the level. Since I don't want to just do collision tests on the whole tile (as it would prevent the sub from getting close to the wall) but rather the section that has the actual wall part (just the line in the tile). I really don't know how to do this, should I switch out the tilemap for just a bunch of line objects and do the collision tests on those or is there a way to do it as it stands now?

# Answer
Collision doesn't need to care about tiles at all. If a tile is just a shape of lines, your "tile collision" is really just collision against those specific lines. You can also use collision against arbitrary shapes defined by mathematical functions - like curves - which are represented by tiles.

Tile collision in this case means determining which tiles the submarine is overlapping in and then doing tests against the lines in those specific tiles. For instance, if tile value `2` is the shape:

```
|\
| \
|  \
----

```

then when the submarine is colliding with any tile of value `2` use the appropriate triangle data to do the actual collision calculation with.

The general technique along with math and some interactive examples can be found at the classic article N Tutorial A - Collision Detection and Response.
> 1 votes

---
Tags: c++, collision-detection, tiles, sfml
---


# Question
Title: Is naming an app similar to another app legal?
I just finished my first ever app after 1 month of programming it and I'm ready to put it on the app store/google play. I searched the stores to see if the name i wanted to name my app was still available. Say i wanted to name my app "example App". I found an app named "exampleApp" but the name "example App" was still available. Could I still legally put my app name as "example App" without worrying about getting sued or having to get my app name changed? The game play and graphics are entirely different. Thanks.

P.S. That app also has over 1,000,000 downloads so if I could still name my app "example app" would that be a bad idea and make it harder for people to find my app? Or would it make my app more popular by someone accidentally finding it in the search?

# Answer
It depends on whether they have registered the name as a trademark. The liability with respect to similarity ("My Product" vs "MieProduct") in specific instances is a matter for lawyers to advise and courts to decide.

> That app also has over 1,000,000 downloads so if I could still name my app "example app" would that be a bad idea and make it harder for people to find my app? Or would it make my app more popular by someone accidentally finding it in the search?

This is why trademark law exists - to prevent brand confusion. If someone actually buys your app thinking it's the other app they heard about then you've harmed the other app's business, or vice versa.

It's also kind of rude to use a name someone has already published, particularly when publishing has an associated advertising cost. While you might have *thought* of using the name first, they may have invested money (or time) into that name already. Thus, you would effectively steal the benefits of their advertising money as well.
> 0 votes

# Answer
You don't have to file/register a trademark for it to be considered "trademarked". If the name has a "TM" after it, then it is trademarked, if it has an "r" in a circle then it is a registered trademark. Regardless, these both mean "finders keepers" with regards to titles and the first person (exampleApp) has somewhat of a legal upper-hand.

People might buy your app if you have a more clever name anyway.
I suggest you start brainstorming :)
> 0 votes

---
Tags: legal, publishing
---


title: Cannot Efficiently Loop SequenceAction

text:
# Question
Title: Cannot Efficiently Loop SequenceAction
Why doesn't this work and how do I fix it/create a different, working loop for this `SequenceAction`?

```
public void setLoopingFade(float time)
{
    fadeLoop = Actions.sequence(Actions.fadeOut(time), Actions.fadeIn(time), Actions.run(new Runnable()
        {
            @Override
            public void run()
            {
                fadeLoop.restart();
            }
        }));

    this.addAction(fadeLoop);
}

```

`fadeLoop` is a `SequenceAction`. I'm adding the `SequenceAction` to an `Actor`.

**Clarification**
Ok, so what I want to do is fade my actor in and out repeatedly. I figured the best way to do this was to create a `SequenceAction` that I would loop. The looping is what the `Runnable` is for. However, this method does not work. The fading out and back in happens once and then nothing. Even though the action is still owned by the `Actor`. I have also tried calling `fadeLoop.reset()`, however, that does not work either and actually makes the issue worse, because, when calling `restart()` I can still restart the `SequenceAction` manually from a different class, but when calling `reset()` the action loses all functionality.
I have tried adding a boolean functionality that would alert the external class to restart the action, but because the action ends after changing the boolean, it is removed from the actor and despite re-adding the action, it still does not work.

# Answer
> 3 votes
Why not using Actions.forever(Action repeatedAction) ?

**Example :**

```
fadeLoop = Actions.forever(Actions.sequence(Actions.fadeOut(time), Actions.fadeIn(time)));
this.addAction(fadeloop)

```

---
Tags: java, libgdx
---