# Question
Title: Possibly a more efficient way to structure my game's map?
I need a little help with structuring my map. I want to make it efficient but I'm not sure if there's a better way to do this:

```
public class Map
{
    Chunk[][] Chunks;
    Object[] Objects;
}

public class Chunk
{
    public int[][] Tiles;
    public List<int> Objects;
}

```

This is the current structure of my map. I basically load and unload chunks if the player is too far from them. Every chunk has the same size, and has a list of objects. For each integer in the list of integers in a chunk, the corresponding Object will be updated in the parent map.

This way, I can handle collision detection without comparing two objects that are far apart: I only compare objects to other objects that are in the same chunk, or neighboring chunks.

However, I'm wondering if there is a better way to structure my map. Faster runtime. Less processing. More efficient.

This may seem like an opinion based question but for those who perceive it that way, the question is how can I improve my map to make it more efficient?

# Answer
If your chunks are square, you could align `Tiles` into a single array, and use a little math to find you indices.

For example:

```
class Chunk {
  final int SIZE = 8;
  int[] tiles = new int[SIZE * SIZE];

  int getTile(int col, int row) {
    return tiles[row * SIZE + col;
  }
}

```

The same this could be applied to `Map`. I'm not sure how much more efficient this is, but I would speculate quite a bit. Instead of making `size` references to `size` arrays, you would have just one array. The computer wouldn't have to track down where each array is in memory.
> 2 votes

---
Tags: tiles, maps, data-structure
---


# Question
Title: Can animation parameters only be changed in scripts?
I have a very simple animation parameter in the Animator, a boolean that is "true" when a shooting animation is playing (to stop the game logic from allowing more shooting during a gun recoil animation). I assumed I'd be able to access this in animations, i.e. setting it to true when a shooting animation started, and false when it ended. But I just can't see how to access it in my animations. It's not available under "Add Curve". Am I missing something?

I can do this in other ways, but this just seemed like the cleanest.

# Answer
AFAIK, yes, the parameters can only be changed via scripts. To stop the game logic from allowing more shooting, you should NOT be making a parameter here. The Animator doesn't need to know anything about that, it only cares about animation blending and transitions.

Make a private boolean variable in the script that actually triggers the shooting and don't trigger the shooting when (e.g.:) \_isShooting is set to true. You can use something like a coroutine to make a set delay.

Animator parameters exist to enable transitions, that's all they do.
> 1 votes

---
Tags: unity, mecanim
---


title: Match-3 Shuffle Required?

text:
# Question
Title: Match-3 Shuffle Required?
How can I detect if there are no more potential matches possible and therefore a shuffle is required?

# Answer
You can always just do a naive approach. Just iterate through all pieces and see if there's a match in any direction, and if you get to the end before any matches are detected, then you have no matches.
> 1 votes

---
Tags: algorithm, software-engineering, procedural-generation
---


# Question
Title: Can I use multiple OpenGL version together
I want to use GLSL but keep my current OpenGL 1.1 setup. The thing is that can I use OpenGL 2.0 shaders on OpenGL 1.1 renders?

# Answer
Until OpenGL 3.0, each version of OpenGL was a direct superset of the previous one, so as long as a graphics card and its drivers support the functions you use, you don't have to worry about compatibility. Also, until 3.0 was released, there was no way to choose an OpenGL version because if you got a newer version than you wanted, you just got functionality you didn't use. You were just given whatever version your driver supported, and there was nothing lost.

So to answer your question, if your graphics card and drivers support OpenGL 2.0 functions and shaders, you can use them without worrying about any code that was designed for 1.1.

Now when OpenGL 3.0 was released, some functions were marked deprecated, and a mechanism to choose your OpenGL version was added. Then beginning with 3.1 some functions were removed. But many people were in situations like yours and still wanted the old functions, so beginning with 3.2 a compatibility profile was added with its own, separate specification.

So once you start upgrading past v3.0, then you have to worry about compatibility a little. In that case, I recommend looking at the specification for the specific version and profile you want to use. It will tell you what should be supported.
> 1 votes

# Answer
If you are using OpenGL ES, no you can't, if you setup an opengl 1.1 context, all shaders & opengl 2.0 calls will fail. You must convert your setup to opengl 2.0. You can keep compatible function calls like glTexImage..., glDraw...etc. But all fixed functions like glTranslate, glMatrixMode(), etc... must be converted to your own matrix calculation mechanism.
> -3 votes

---
Tags: opengl, java, graphics-programming, lwjgl
---


title: Accelerometer based games smoothness

text:
# Question
Title: Accelerometer based games smoothness
Take Doodle Jump and other games that rely on the accelerometer. The movement of the character is very smooth and I have no idea how they implemented it. I've seen a number of SO/GameDev/forum questions, but the discussion ends abruptly when someone recommends a high/low pass filter. I've tried that (unless I'm missing something) and the results are nowhere near smooth.

All I'm trying to do is move a character on the x axis. This is the code I have and it's very "choppy". It's actually the code you can see on the official Android tutorials.

```
float alpha = 0.9f; //tried many values from 0.1f to 0.99f. chopiness still there

@Override
public void onSensorChanged(SensorEvent event) {
    if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        if(init) {
            gravity[0] = event.values[0];
            gravity[1] = event.values[1];
            gravity[2] = event.values[2];

            init = false;
        } else {
            gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
            gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
            gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
        }

        // Remove the gravity contribution with the high-pass filter.
        linear_acceleration[0] = event.values[0] - gravity[0];
        linear_acceleration[1] = event.values[1] - gravity[1];
        linear_acceleration[2] = event.values[2] - gravity[2];

        character.setX(character.getX() - linear_acceleration[0]);

    }

```

I also tried multiplying `linear_acceleration[0]` with a sensitivity, where `0 < sensitivity < 1` but the choppiness still doesn't go away. What is the next step from here to achieve a smooth movement like in Doodle Jump?

# Answer
OK, I managed to sort this out and it was a bit stupid. Yes, the low-pass filter DOES solve the problem. Actually here's my code (note I'm doing it in a different method, but just copy and paste the contents in `onSensorChanged(SensorEvent)` if you wish:

```
private static final float alpha = 0.65f;
private static final float SENSITIVITY = 1f/128;
private boolean firstTime = true;

@Override
public void handleSensorEvent(SensorEvent event) {
    if(firstTime) {
        vals[0] = event.values[0];
        vals[1] = event.values[1];
        vals[2] = event.values[2];
    }

    vals[0] = vals[0] + alpha * (event.values[0] - vals[0]);
    vals[1] = vals[1] + alpha * (event.values[1] - vals[1]);
    vals[2] = vals[2] + alpha * (event.values[2] - vals[2]);

    character.setX( character.getX() - vals[0] * SENSITIVITY );
}

```

You can calibrate `alpha` and `SENSITIVITY` according to your needs. Now this is why this code was producing very choppy movement initially: in my activity's `onResume()` I was registering my listener using `SensorEvent.SENSOR_DELAY_NORMAL`. That is *wrong*. What you have to do is register it with `SensorEvent.SENSOR_DELAY_GAME`. I think the reason behind this is obvious. So in your activity's `onResume()`:

```
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);

```

where `accelerometer` is declared as (in `onCreate()`):

```
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

```
> 1 votes

---
Tags: android
---


title: Gamemaker multiplayer using 39dll

text:
# Question
Title: Gamemaker multiplayer using 39dll
I am making a gamemaker multiplayer game using 39dll's tcp sockets. As I want to host the server (and my javascript knowledge is a lot better), I use node.js for the server. I have already got gamemaker to connect to the server and send data, but now I have a problem with receiving data. After reading a lot, it seems that I need to do that like so: `sock=tcpaccept(global.tcpConnection,1);`. If sock is a negative number, the creation of the 'listening' interface failed. It returns me the number `-10022`. I can not find much information about it, so if anyone knows why this problem occurs and how to fix it would be very nice.

I am just making a normal gamemaker 8.1 game, no HTML5 game (I'd rather script that myself, not with gamemaker as I am really disliking it).

My server code:

```
var net = require('net');
var server = net.createServer(function(socket){
    console.log('connection made');
    socket.on('data', function(d){
        console.log(d.toString());
        socket.write(d.toString());
    });
    socket.on('error', function(e){console.log(e)});
    socket.on('close', function(){console.log('Socket closed');});
    socket.write('hhhaaannbikbkm');
}).listen(process.env.VCAP_APP_PORT||8080);

```

GML code (in the game start event):

```
dllinit(0,true,true);
global.username = get_string("Gebruikersnaam:","");
global.serverip = get_string("Server IP:","127.0.0.1");
global.serverport = get_integer('port', 8080);

global.tcpConnection = tcpconnect(global.serverip, global.serverport, 1);
setformat(2, '<!SEP!>');
if(!tcpconnected(global.tcpConnection)){
    show_message("Connection failed");
    game_end();
} else {
    setnagle(global.tcpConnection,1);
    clearbuffer();
    writestring(global.username, false);
    sendmessage(global.tcpConnection, 1, 1);
    while(true){
        var sock, size, cnt;
        sock=tcpaccept(global.tcpConnection,1);
        show_message(sock);
        //if (sock <=0) break;
        setsync(sock,0);//block untill new package
        size = receivemessage(sock, 0);
        show_message(size);
        //setsync(sock,1);//unblock socket
        cnt = readstring(0, '<!SEP!>');
        if(cnt!=''){
            show_message(cnt);
            clearbuffer();
            writestring(cnt, false);
            sendmessage(global.tcpConnection, 1, 1);
        }
    }
}

```

# Answer
I already fixed this like a week ago or so. I just don't need to call `sock=tcpaccept(global.tcpConnection,1);`, but just receive the messages with `receivemessage(global.tcpConnection, 9999999);`
> 0 votes

---
Tags: node.js, game-maker
---


# Question
Title: Custom Physics: Preventing objects from losing velocity in certain situation
Illustration: http://s22.postimg.org/7agd30vap/Untitled.png

So the little box is my character. The red arrow shows the current velocity(Some force to right + gravity). Below it are 2 blocks which has the same height. The problem is that my algorithm would false solve the collision normals.(You can see them in green). These would mean that my character would not slide, but will stop in one place.

I'm following this tutorial: http://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6331

Is there something I miss and how can I fix this problem?

# Answer
> 0 votes
This is a non-trivial problem. See http://www.reddit.com/r/gamedev/comments/1w92dm/2d\_collision\_detection\_and\_resolution\_solving\_the/, https://www.iforce2d.net/b2dtut/ghost-vertices .

If all your blocks are axis-aligned, the easiest solution would be to prioritize collisions with normals along the y-axis.

One common solution is to use "rounded" corners for your character box. Another could be to use line segments instead of blocks (if the blocks are supposed to be static) - google "box2d chain-shapes" .

# Answer
> 0 votes
I solved this problem once by creating a 'rail' (which was just a line located above all blocks.) A rail would exists above all blocks and govern the horizontal and vertical movement of the character. Two rails that touched would connect to each other, allowing the character to move seamlessly from one block to another. If the character touched a block and a rail at the same time, they were moved to the rail and 'locked' to it. If the character touched a block and a rail at the same time, they were moved to the rail and 'locked' to it. While on the rail, walking animation took place, physics was suspended, collision detection with lower blocks was disabled and jump was enabled. If the character walked off the block or jumped, they would 'fall' off the rail.

---
Tags: physics
---


# Question
Title: What are the benefits of using an entity ID system?
I'm currently reading the book Programming Game AI By Example.

The book mentions assigning unique ID numbers to each entity in the game. Often when entity **A** needs to contact entity **B**, **A** gets a reference to **B** by sending **B**'s ID number to an **EntityDatabase** class. This class recieves ID numbers and returns references to the entities.

The ID numbers of some entities could also be fetched from a file containing the IDs of some of the entities (the main game characters).

My question is: Why would I do this? Why can't I work directly with references? Is it sometimes difficult to get a direct reference? Is using an ID system a common approach? Are there games that don't use IDs?

I'm new to game development. **Please explain the benefits of working with an entity ID system.** The advantages and disadvantages. Concrete examples would be great. Thanks

# Answer
> 18 votes
References work well for many situations. However, there are three important situations in which references won't work well:

* **Networking**. When sending information about synchronizing the state of entities over the network, references can't be used. You'll need to identify the entity in some way so the remote machines know who you're talking about.
* **Saving/loading**. When saving the state of your game to disk, the object references can't go with it. That means when you're loading the state, Entity A that had Entity B targeted by a reference no longer knows who to target. The memory locations are different, the objects are different.
* **Memory management**. Having a central place to store references means that when deleting an entity, you don't have to go through all your entities and remove references to it for the memory to be cleaned up. References should only be used when needed, then removed in any other entity. Reducing reference counts ensures you don't have zombie entities that are only referenced by the last thing they interacted with or some other entity. This also helps to avoid null references with a standardized way of testing if an entity still exists.

# Answer
> 2 votes
One last thing is that if you are using the Object Pool pattern and an entity gets reset because the creature died (for instance) and respawned somewhere else, a reference will still point to the same entity (fault) and an ID will no longer remain valid.

ID 5067 points to address 0x8765 creature dies and another spawns new creature ID is reset to 7073 Someone checks for ID 5067, it points to 0x8765 but that creature is now registered with the ID 7073 so the entity ID database knows you used an obsolete ID and informs you, the creature you have tried to reach is no longer active.

That and all the wonderful reasons Byte56 mentioned are why it is a good design to avoid using references directly.

---
Tags: architecture
---


# Question
Title: Mentality for the hard initial stage of game development
I feel like there is a lot of excitement involving the initial steps towards developing games. Kids (myself younger self included) get very excited about making games and talk for hours about the games in their imaginations. Then comes the initial game making experience. A lot can happen there. It feels like a no-man's land where many enthusiasts fall away. It seems to me that there are a lot of good, talented people out there who end up stuck in the mud. Is that just the nature of competition and a necessary hurtle to greatness or should something be done to avoid it? I feel that experienced game designers with a history of success could offer a lot of help, but then again, sometimes people are punished for our kindness. However, I feel that having the right mentality would both help a person get through the hard times and make it easer to approach professionals. Could I get some tips on crafting a positive and effective mentality regarding these issues during the early staged of a game design career?

# Answer
> 2 votes
That is a very tough question. The only advice I can offer is to procrastinate as little as humanly possible. If you are impulsive and often procrastinate and get tempted easily into doing other things with your time, you might want to learn how to limit your procrastination.

Another piece of advice is to think about your game as tiny atomic pieces that are joined together to make a game and then throw them all in a bad and pick one shiny atom and focus only on that specific piece and make that work great! Afterwards if you make it that far, decide if another piece is needed and work about adding that too.

For instance, if you wish to make a 2d adventure game, your higher level list may look like this:

* Procedurally generated maps
* Procedurally generated weapons
* Procedurally generated monsters
* Epic boss fights
* Item shops
* Huge towns
* Spells
* Potions
* Classes
* NPC companions
* Pets
* Advanced combat system
* ...

So lets see, what is in the core of all this, what is absolutely needed to get started? Your low level list might be more this:

1. You need a square that moves around in an empty area.
2. Add a simple (preferably existing collision system) and some obstacles
3. Add moving destroyable obstacles (with hp)
4. Make the square attack whatever is in-front of it when the player hits "A".
5. Make a moving obstacle that attacks back.
6. Put a tiny image on top of the square.
7. Add a sound when the player hit successfully.

People often get caught up with ideas they think are great but making those things happen in the game the right way is lots of work and if they don't see results, they lose all focus and stop working. You need to set simple (almost idiotic) goals and do at least one every week or you will never finish.

# Answer
> 1 votes
The most important thing to keep in mind is to take it slow, one step at a time. There are many areas where a new game developer can make himself noticed. Focusing on the elites and their activity while at the beginning will only make you seem small, while making the workplace seem daunting, and that's not a good way to go.

Aim at smaller companies, smaller projects and smaller goals at the start. Competition there won't be extreme, you won't be surrounded by elites, and you'll be able to develop yourself at an appropriate pace. Most importantly, these opportunities will help you appear trustworthy and experienced while advancing through your career.

You will see that the more you go through, the easier it is to approach other professionals in their work. It's all part of "going through" after all: dealing with people. And to deal with people you have to be there. To be there, you have to start somewhere. Don't build up preconceptions about how that somewhere will look. You'll most likely be surprised in the end.

---
Tags: career
---


# Question
Title: How do I get hardware accelerated graphics and shaders in PyGame?
I have created several simple games with PyGame, but until now, I have focused on mechanics rather than graphics. The graphics in my games have been extremely rudimentary, consisting of basic shapes on black backgrounds.

I've recently decided to change that and create a 2D graphics engine supporting proper texturing, some animation, and most importantly: lighting. While researching these, especially the last, I've started doubting whether PyGame is the right tool for this. Many tutorials concering implementation of lighting, shadows, et cetera recommend using techniques such as GPU shaders and pixel-level manipulation.

Looking at the documentation of PyGame, I don't see anything that would let me implement such things with any degree of efficiency. I can access bitmaps directly with `PixelArray`, but doing any significant processing this way seems like it would be a performance nightmare.

How can I get hardware accelerated graphics, vertex and pixel shaders when making a game with PyGame?

# Answer
PyGame itself, being a wrapper around SDL, is unable to directly use hardware acceleration. You can, however, use PyGame to create an OpenGL context and then render into that via an OpenGL library like pyglet or PyOpenGL, which will let you then also use GLSL vertex and fragment shaders.

This blog post does a good job of explaining the basics of using PyGame in conjunction with each other (domain now not working but archive available on archive.org).
> 7 votes

---
Tags: graphics, pygame
---


title: Is host advantage real?

text:
# Question
Title: Is host advantage real?
I'm sure many of you have heard the term ***host advantage*** through out your time playing action video games. However, I was curious if this was a real studied and proven concept in game design, computer science, and network programming? I tried looking it up on Google, but all I saw was just some gamers ranting back and forth on a forum (none of them even seem to bring up client-server concepts in their babbling...).

# Answer
The essence of the "host advantage" is having a low ping (round trip time to the server). If you are the server, you'd have no ping time, but even being really close to the server would result in a small ping and still have a large "host advantage", so I'm just going to call it a "low ping advantage" instead.

It really depends on the game and how the networking code is written. Some games/engines will publish this information, but many more won't, so I'll take a few examples:

**First person shooters** (FPS) are likely where the vast majority of low ping complaints come from because *you* always shoot first, right? Valve describes how the Source Engine handles networking (Counter-Strike:Source, Left 4 Dead, Titan Fall, etc.). The article goes into great depth, so I will attempt to gloss over some of the details:

> Entity interpolation causes a constant view "lag" of 100 milliseconds by default

and

> Command Execution Time = Current Server Time - Packet Latency - Client View Interpolation

In effect, all clients are looking slightly into the past in order to help compensate for reasonable ping times. In theory, if clients are looking 100ms into the past, and if all players can get their actions to the server & other players within that time frame, then everyone should be looking at the same picture of the world at all times and everyone will be happy. But what happens when two players shoot within 100ms of each other? It will still take time for the shot information to reach the other clients, so both players may still see themselves shoot, even though there can only be one survivor. This likely creates a lot of false-positives. Since ping times aren't going anywhere anytime soon, there will always be "who shot first" arguments.

This still leaves the question: is it better to have a low ping? In the case of the Source Engine, I would argue that there's no advantage to have pings lower than ~50ms (about half of the interpolation time with default settings), but it will vary by game and can be affected by many external factors like packet jitter.

The answer gets a bit fuzzy when you start to consider high pings though. Those high ping players may not have an accurate view of the world, AND the other players may not have an accurate picture of the high-ping player. This can cause a variety of issues for everyone. Games handle this situation in various ways, and there is no clear solution. You can increase the interpolation time to make it more fluid for high-ping players, but then there will be more situations where one player thinks they did something before another. Decreasing the interpolation time will make it worse for high-pings, but fewer Hans shot first situations. Until ping times are non-existent, there will always real-time communication issues.

**Age of Empires** uses a what I'll dub a "buffered lock-step approach" as described in this article. There is some debate, but StarCraft and other modern strategy games likely use a similar method. Again, it's quite detailed and technical, so I'll gloss over it.

> The game would tend to pause or slow only at the very worst spikes- command latency would go up but would stay smooth

There is no advantage for a low ping in games that use this method because each block of commands is executed in-order, at the same time, on all machines. You can read the article for more details on how.

Only real-time games are affected by a low ping advantage, and most real-time games will fall into one of the two categories above, which leads me to conclude that extremely low pings are no better off than medium to low pings.
> 4 votes

---
Tags: networking, client-server, online, client, hosting
---


# Question
Title: Publish android game only for 800 x 480 resolution in portrait mode
I have developed a game in libgdx. I worked for long and after finishing, I found that the game runs perfectly only on devices with resolution 800 × 480. I found this solution:

```
<compatible-screens>
    <!-- all small size screens -->
    <screen android:screenSize="small" android:screenDensity="ldpi" />
    <screen android:screenSize="small" android:screenDensity="mdpi" />
    <screen android:screenSize="small" android:screenDensity="hdpi" />
    <screen android:screenSize="small" android:screenDensity="xhdpi" />
    <!-- all normal size screens -->
    <screen android:screenSize="normal" android:screenDensity="ldpi" />
    <screen android:screenSize="normal" android:screenDensity="mdpi" />
    <screen android:screenSize="normal" android:screenDensity="hdpi" />
    <screen android:screenSize="normal" android:screenDensity="xhdpi" />
</compatible-screens>

```

But it allows various other resolutions too; Is there any way that I can publish my game only for 800 × 480 resolution?

# Answer
> 0 votes
There are ways to restrict the screen types your app will be distributed to, as described here, but I don't think it gets as specific as you want, and I'm not sure why you would want to make it that specific. It would restrict your market to a very tiny subset of all Android users. You can put a warning in the description that it only works on certain screen resolutions, if you want, or you can change things to support a larger set of resolutions.

In the latter case, there are plenty of other questions and answers on this site addressing that issue. I recommend this answer in particular, to get you started.

# Answer
> 0 votes
I use a framework called MTX that works on top of LibGDX, so my answer may be different. I am not saying to redo your whole game in MTX, that would be silly. However the framework is open-source, so you can figure out how everything is done with a little bit of looking.

You mainly need to look at 2 main things:

* Resolution
* Aspect Ratio

You mentioned a target resolution of 800 x 480, therefore the aspect ratio is ~1.666667. I would set these in some global class made just for resolution:

```
TARGET_WIDTH = 800;
TARGET_HEIGHT = 480;
TARGET_ASPECT_RATIO = TARGET_WIDTH / TARGET_HEIGHT;

```

Now we need the current information:

```
CURRENT_ASPECT_RATIO = Gdx.graphics.getWidth() / Gdx.graphics.getHeight();

```

What we want to do here is to scale everything while maintaining the aspect ratio. So not every screen is going to be 5:3 specifically, but we can fit the game into 5:3 as best we can and simply constrain the gameplay elements within that area. Anything outside of that area can be background so as not to waste the space.

I am assuming that any device is forced into landscape mode.

```
WORLD_SCALE = 1;
WORLD_WIDTH = SCREEN_WIDTH;
WORLD_HEIGHT = SCREEN_HEIGHT;

if(CURRENT_ASPECT_RATIO < TARGET_ASPECT_RATIO)
{
    //Filler is on top and bottom
    WORLD_SCALE = Gdx.graphics.getWidth();
    WORLD_HEIGHT = TARGET_HEIGHT * WORLD_SCALE;
}
else if(CURRENT_ASPECT_RATIO > TARGET_ASPECT_RATIO)
{
    // Filler is on left and right
    WORLD_SCALE = Gdx.graphics.getHeight() / TARGET_HEIGHT;
    WORLD_WIDTH = TARGET_WIDTH * WORLD_SCALE;
}

```

What this does is finds out your working area. It will fit to whatever size screen, either by length or by height. By applying world scale, we also ensure that your objects scale up for larger screens as well.

For example, my phone has a screen that is 1920x1080. It has a higher aspect ratio than 800x540, and therefore we need to put some bars on the side. This would give me a WORLD\_SCALE of 2, a WORLD\_HEIGHT of 1080, and a WORLD\_WIDTH of 1600, trimming 160 pixels off both sides.

Now it's too late at night for me to go into detail about how to use these values specifically, but it's pretty straightforward. You construct a Viewport object using the newfound values to size and center it. Ensure that your worldWidth and worldHeight for the viewport match your TARGET\_WIDTH and TARGET\_HEIGHT. Then you can construct your Stage using the new Viewport.

This stage should now be correctly fitted to maintain your desired aspect ratio, while scaling everything to fit the screen as much as possible without messing up the aspect ratio of your game.

---
Tags: android, libgdx, resolution, google-play
---


# Question
Title: Is there any way to change texture filtering globally in Direct3D 11?
One of the major changes I have encountered between Direct3D 9 and Direct3D 11 is the new API for setting up texture sampling. In D3D9, it was sufficient to simply set a given value of a given property to a given sampler index and safely assume that state would remain (and be unaffected by other state changes) for as long as was needed by the application.

```
direct3Ddevice->SetSamplerState(samplerIndex, D3DSAMP_MAXANISOTROPY, value);

```

However, in D3D11, the process is a little more involved. First you create and populate an object of type `D3D11_SAMPLER_DESC`, then from that object create an `ID3D11SamplerState`, then apply that to a sampler index.

```
D3D11_SAMPLER_DESC desc = CD3D11_SAMPLER_DESC(CD3D11_DEFAULT());
desc.MaxAnisotropy = value;
ID3D11SamplerState * state = 0;
direct3Ddevice->CreateSamplerState(&desc,&state);
direct3Dcontext->PSSetSamplers(samplerIndex, 1, &state);

```

I understand that this is designed to minimise the number of queued requests per frame by batching potentially a whole bunch of state changes into one object... However, if the developer wanted to, say, put a global anisotropic filtering setting in their game's options screen, they'd need to keep copies of the sampler descriptions of every sampler they use for every shader (to ensure that no other parameters would get lost), then iterate through all of those copies to apply the new filtering level, and recreate all those state objects.

Surely there must be a simpler way to apply a single sampler setting globally for an application?

# Answer
No, there is not a simpler way. As you said, you must recreate all sampler objects that are affected by a change.

However, it doesn't have to be a lot of work. Typically, you can share a few samplers across many shaders. I typically have a single sampler with trilinear/aniso filtering and repeat addressing, reused for textures across all shaders. If the aniso setting is changed, only that one sampler needs to be recreated. I have another sampler with bilinear filtering and clamp addressing that's reused for all image resizing/postprocessing operations, and so on. You don't need to (and probably shouldn't) create a separate sampler object for every shader or texture.
> 4 votes

---
Tags: textures, directx11, graphics-programming, filtering
---


title: Do Java and Actionscript use OpenGL?

text:
# Question
Title: Do Java and Actionscript use OpenGL?
As far as I know there are only 3 base graphics libraries on Windows, the GDI, OpenGL and DirectX, is that correct, so that means that Java, Actionscript and all language use one of these 3 libraries if they are to display graphics, or maybe Java has it's own graphics library/API?

# Answer
> 3 votes
Nick already gave a more specific answer, but I get the sense from your question that you'd benefit from a more generic answer.

Different platforms have various ways of getting pixels to the screen.

Software is written in layers. You can implement OpenGL on top of D3D (like Microsoft has done), or even on top of GDI as software rendering (like Microsoft did in older versions of Windows). It's also common to implement different versions of graphics APIs on top of each other (like OpenGL ES 1.0 on top of OpenGL ES 2.0).

Microsoft also has an old graphics API called WinG, which can work even on the latest Windows versions; the output just goes through GDI instead of through specialized drivers.

Conversely, you can also implement DirectX on top of OpenGL (and there are some such open source projects out there, with WINE including one implementation). And since modern windows uses hardware acceleration for GDI, I wouldn't be surprised if the modern GDI was actually "kind of" implemented on top of DirectX.

Now, we have some cross-platform systems such as Java or WebGL. These generally offer the application developer one (in case of WebGL) or multiple (in case of Java) graphics APIs. What those APIs use to get the pixels on screen depends on the implementation at hand.

For WebGL, Firefox (for instance) actually uses Direct3d as the back-end on Windows. On Linux, I'm pretty sure it uses OpenGL instead. On mobile devices the same will undoubtedly use OpenGL ES (although I'm not sure if mobile browsers support WebGL).

# Answer
> 4 votes
Java defaults to using GDI (AWT, Swing). JavaFX supposedly will be able to make use of OpenGL in future. Java + LWJGL (an OpenGL wrapper that accesses native opengl32.dll via JNI) provides more direct hardware-accelerated support for Java.

Flash Player 11 onward made use of OpenGL via `Stage3D`. Without using `Stage3D`, it is using a software renderer built to work within the browser. All browser output gets routed through the selected desktop renderer, which may be either GDI / software or hardware accelerated, dependent on user display settings.

Unity uses OpenGL as well, since you are asking about "all languages". Python uses GDI unless PyOpenGL, DirectPython or similar is explicitly used instead. Native instructions via e.g. C or Assembly again use either GDI or access OpenGL / DirectX directly. Back in the days of Glide, it was a similar story; a DLL provided API access to the underlying graphics hardware.

---
Tags: opengl, java, graphics, actionscript-3
---


# Question
Title: Understanding the Seek steering behavior
I'm currently studying steering behaviors. Have recently learned about Seek.

I have a question about this.

Seek is supposed to turn the agent slowly in the direction of it's target, and then move in that direction.

However, I don't understand how Seek turns the agent around slowly. It seems to me like it should make the agent change direction immediately.

This is the code for a Seek function:

```
Vector Seek(Point target){

    Vector toTarget = new Vector(target - agent.getPosition());
    Vector desiredVelocity = toTarget.normalize() * agent.getMaxVelocity();

    return desiredVelocity.subtract(agent.getVelocity());

}

```

And then here is the `update()` function of the agent.

```
void update(){

    Vector force = seek(target);
    Vector acceleration = force.divideBy(mass); // mass = 1.
    velocity = velocity.add(acceleration);
    position = position.add(velocity);

}

```

Anybody mind explaining to me where the **gradual** change of velocity takes place? Thanks

# Answer
> 2 votes
That function gives you a direction scaled such that it indeed performs an instantaneous velocity fix, if added to your velocity. You can think of this as the "steer direction". You can scale this direction by whatever factor you like. Maybe something like this to get started:

```
const dt = (1.0 / 60.0);
object.velocity += dt * object.Seek( targetPosition );

```

A scaling factor of 1 would provide an instant change, and lesser than 1 would apply a partial change.

If you want your steering behavior to preserve constant velocity, you'd probably want to just rotate your velocity vector towards the target, instead of adding/subtracting vectors.

In your example code `acceleration` is used as the seek vector, and scaled by a factor related to mass. The larger the mass of `agent` the greater the divisor of the steer vector. This is like scaling in the range of 0 to 1 with inverted mass:

```
velocity += direction * (1.0 / mass);

```

You can see from above that if your mass is 1, then an instant fix will occur.

However, steering with the rate of change dependent on mass might be silly for most games. Usually you just want to directly tune the scaling factor by hand as a designer, within a range of 0 to 1 (or negative, or higher than 1 if you want):

```
velocity += direction * scalingFactor;

```

# Answer
> 1 votes
This function appear strange because it does not actually compute force, it compute the delta in velocity (the change in velocity) which is needed in order for the agent to turn and pursue the target. It has nothing to do with force and mass and yet those are artificially squeezed in there for no reason.

If you want gradual change, compute the desired change (like you already do) and make partial changes each frame. This could be done in several ways, one is to cap the acceleration like you do with the velocity. The other is to compute the desired change and then multiply it by some fraction.

The change is gradual only when `acceleration` is *bound* or partial (e.g. 10% of the needed acceleration). Whenever acceleration is used to change velocity and velocity is not changed instantly to a new value, you get the desired gradual smoothness. In this case there does not appear to any gradual change. It appears that the change is instant. This is because the acceleration is not capped or multiplied by some fraction e.g. 0.05.

If you wish to make change smooth and gradual, simply multiply the acceleration by some fraction such as `deltaTime` (frame time) and perhaps cap it with some maximal value. Otherwise you are just setting the new velocity to the desired velocity for pursuit.

You can use:

```
acceleration = acceleration.normalize() * agent.getMaxAcceleration();
velocity = velocity.add(acceleration);

```

@RandyGaul was the first to answer correctly

---
Tags: ai, steering-behaviors
---


# Question
Title: Is there any reasons to make sprites and bodies line up?
So in LibGDX the Sprite objects position is where it's 0,0 mark is in the word. In Box2D a a bodies position is in it's center. So to line these up when you update the sprites position with the bodies position you would adjust it by half the width and height. But it seems to me theres no reason to worry about that. Because the relative position is always going to be the same, and that it'll just waste calculations lining it up. Is there any reason I should do it?

# Answer
> 0 votes
Just make sure your sprites aren't going outside the canvas if you don't want them to and I think it's fine. You'd just have to alter the boundaries for the bodies in relation to the canvas in that case.

---
Tags: physics, libgdx, rendering, box2d
---


# Question
Title: Detecting Light Intensity Around Characters
**Later Edit**

Since there seemed to be a bit of confusion: I am asking this for purely didactic reasons, I'm not searching for the most efficient solution. Reformulated question: I'm working under Unity, and I'd like to know if it would be possible to somehow query the material + shader of each GameObject that has a Mesh Renderer attached to itself, in order to find out how much light has fallen on the 3D model. I'm not very experienced in computer graphics, so this may seem like a stupid question. I'm thinking of something along the line of pixel by pixel comparison of a texture's brightness at any given point in time.

# Answer
> I'm working under Unity, and I'd like to know if it would be possible to somehow query the material + shader of each GameObject that has a Mesh Renderer attached to itself, in order to find out how much light has fallen on the 3D model.

As per Unity's documentation, Unity does not provide such functionality, so it's not possible to achieve what you want.
> 1 votes

# Answer
A quick and dirty solution might be to get the position and intensity of nearby light sources and calculate intensity/distance for each, taking the greatest value to be the light level (if you're just after relative levels rather than pure accuracy, such as you might want when making a minecraft clone and deciding whether creatures spawn or not depending on darkness).
> 3 votes

---
Tags: c#, unity, lighting, materials
---


# Question
Title: Store custom data against XboxLIVE Gamer in XNA?
If I am using Xbox LIVE Gamer Services for a networked XNA game, is there anyway to store custom data against the `Gamer` or `GamerProfile` so should they sign-in again even on a different machine I can access it? For example if I want to store their colour choice.

# Answer
This is possible, but it depends on user choice in order to function.

The method you mentioned, using Gamer Services, will not accomplish what you described. That corner of the framework only serves up player default settings, not game-specific settings. I believe color choices are included in that information. But again, this is not their choice for *your* game, it is their default choice for all games. (Gamer services does allow setting temporary status info.)

You will need to store custom data in the same manner that you would generate a save file, with User Storage. The process flow described in that article notes that you must call `StorageDevice.BeginShowSelector`, which displays the HDD/Memorystick/Cloud choices. This is why your solution depends on player choice.

*IF* the player selects cloud storage on the first machine, and *if* they also select it on subsequent different machines, then they have access to the same saves in both locations. If they choose local physical storage, that information is stuck on the single machine.
> 1 votes

---
Tags: xna-4.0, xbox-live
---


title: Should I use scenes in Unity for menus?

text:
# Question
Title: Should I use scenes in Unity for menus?
I assume scenes are for different levels, but should I use them for menu screens or is there a specific tool for menu screens?

# Answer
It depends on the usage.

If you have a menue that is shown upon the start of game ( e.g. main menue ), then it's quite obvious that you want to treat it as a scene. However, when you have simple little menu that is used quite often then it's not really wise to reload the scene each time. Especially when you're having some pause menu.
> 7 votes

# Answer
The general rule is that a scene is a thing that has it's own distinct processing regimen. If none of the logic running is the same as that of another part of the application, then they should be two distinct scenes.

OTOH, if for instance you are doing level flythroughs behind your main menu (think MineCraft), then you probably want to adapt your in-game scene, such that you e.g. have no player input, and menu overlays are present and active instead... because running the scene is a lot of logic you don't want to have to repeat.
> 5 votes

# Answer
For the main menu screens if you are using UnityGUI, you can use more than one camera for different GUIs, in one scene. For example, when you press Play at the start menu, the current camera turns off and another camera which shows, say a Car Selection menu, turns on. All these happen in one scene.
> 1 votes

---
Tags: unity
---


# Question
Title: How can I tell what a rectangle intersects with?
I understand XNA's `Rectangle` class is rather limited, but surely there is a way to tell what a `Rectangle` is intersecting with?

If I had `Rectangle boundingBox = new Rectangle(stuff here);` how would I retrieve what is currently (if there is anything) intersecting `boundingBox`? Is there any easy method to detect if *anything* is intersecting it instead of testing with two individual rectangles with `boundingBox.intersects()`? Similarly, if this is possible, how would I retrieve what rectangle it is colliding with?

If there isn't any easy way of doing it, how would you go about implementing this if you had loads of possible rectangles you want to hit-test?

# Answer
> 5 votes
No, there's no way to do this. What you're looking for is a container, that holds references to rectangles that are insides its bounds. This isn't an easy thing to do when you really think about it.

There is no way for the rectangle object to know any other rectangle object exists, let alone know if one is inside of it or not. However, there is a few data structures that do what you want.

For 2D, which I'm assuming you're working in, there's a structure called a Quadtree. A Quadtree can start as a single container spanning the entire map. Now, as you add collidable objects to your game, you must ( manually ) add those objects to the quadtree. The quadtree can then split up into smaller areas recursively depending on the number of objects in the game. The result is that you can pass the quadtree a rectangle, and it can quite quickly return to you all the rectangles that lie in that area.

However, moving objects around the quadtree is a whole other story. Here's a better explanation: http://en.wikipedia.org/wiki/Quadtree

Of course, I wouldn't recommend over complicating things. Unless you're building a fairly complex game, there's nothing wrong with checking every rectangle with each other.

# Answer
> 1 votes
As far as I know, most programs will separate geometry for rendering from geometry for physics. (This is because rendered models can be incredibly detailed, and hit testing against each polygon will take way longer than say, a couple quadtree intersection tests.)

If you're using a small number of simple rectangles, you could simply test each rectangle against every other rectangle that exists. This is O(n^2), though, so it will scale dramatically as the number of rectangles increases; when performance starts to suffer, you should look into more "organized" collision detection/physics processing schemes.

---
Tags: xna, 2d, collision-detection
---


# Question
Title: glDeleteTextures - release data, but keep the texture ID?
In OpenGL, is it possible to release texture data, but keep the same texture id? I want to unload textures when they aren't needed, but load them again later when they *are*.

There are a lot of objects that store texture IDs. (For example - spritesheets - multiple objects use the same texture ID and represent a part of the image). `glDeleteTextures` releases the id, so another texture (image data) can acquire the same ID. I'd have to walk all objects and change the texture IDs they use.

Is there a way to release the *texture data only*, but keep its ID, so that later I could do only `glTexImage2D` on the same ID and keep all references to this ID valid?

# Answer
As Ben suggested, you could use a dummy call to `glTexImage2D()`. If setting a 0x0 texture doesn't work, you should be able to create a 1x1 texture. I've seen the WebKit source code do something similar to "allocate" texture IDs, and then call `glTexImage2D`/`glTexSubImage2D` to upload the actual texture data later.

Of course, it's up to the driver whether it wants to free the memory at that point. OpenGL doesn't provide direct texture memory access, unless you use an extension like EGL\_KHR\_Image to do platform-specific management.
> 1 votes

---
Tags: opengl, textures, memory-efficiency
---


# Question
Title: Workaround the flip queue (AKA pre-rendered frames) in OpenGL?
It appears that some drivers implement a "flip queue" such that, even with vsync enabled, the first few calls to swap buffers return immediately (queuing those frames for later use). It is only after this queue is filled that buffer swaps will block to synchronize with vblank.

This behavior is detrimental to my application. It creates latency. Does anyone know of a way to disable it or a workaround for dealing with it?

The OpenGL Wiki on Swap Interval suggests a call to glFinish after the swap but I've had no such luck with that trick.

# Answer
The "flip queue" that feeds the back buffer is nowadays closely tied to double/triple buffering, as there are almost no implementations that copy the back buffer into the front buffer anymore.

You may be setting the swap interval to 1; try setting it to 0, instead. This will disable vsync, but should improve your latency measurements. Ways of reducing latency are highly driver-specific, and you should check the manufacturer site for OpenGL optimization guides/best practices, or something similar.

Most graphics drivers have terrible latency, and coupled with latencies in displays, users generally experience input lag on the order of ~100 ms. By the way, this is what allows cloud gaming services to work, as users are so used to this latency that they won't notice a 70 ms round-trip to a server that is rendering the frames.
> 1 votes

---
Tags: opengl
---


# Question
Title: Level loading works in Unity editor, but quits when deployed
In my level selection screen, all but the first level start out locked.

When I click on a level, it loads perfectly in Unity editor. However, when I build the game on a real device, the game stops as though I had pressed the back button on my device instead of launching the level.

What happened? How can I debug this, given it works fine in the editor?

# Answer
When building your game, Unity will not include all the scenes by default. Ensure that your scene is included and checked in the build window. The build settings window appears after selecting build and displays the currently selected scenes to be built. You can also find it by selecting File-\>Build Settings. You may need to add the scenes yourself and then ensure they're checked to be included in the build.
> 3 votes

---
Tags: unity, loading, levels, debugging
---


# Question
Title: Render scene twice in OpenGL, overlay second render with tranparency
Is it possible to render two scenes (same scene with different setups) without any alpha, and after that is done just overlay the result from the second render on top of the first layer with a static transparency?

And how do I do it? I want it fast so the transparency should not be implemented during rendering, only on the final overlay process.

Basically I am asking for an efficient OpenGL post-processing method to combine the two different renders when drawing to screen.

# Answer
> 2 votes
Yes it seems you do want a post processing effect.

First Render your scene normally. Then sample this texture in your next Render technique but use a set alpha.

something along the lines of:

```
in vec2 Texcoord;
out vec4 outColour;
uniform sampler2D tex;

void main()
{
   outColour = texture( tex, Texcoord );
   outColour += vec4( outcolour.rgb, 0.5f );
}

```

This is not tested and I'm only guessing that this is the effect you will want. The `0.5` in the second line of main can be cahnged for whichever alpha value you would like.

As an added note, you could do this in your original render pass, as soon as you know what the final color for the pixel will be, then you can just do that that last line of the shader with your own predefined alpha value.

---
Tags: opengl, transparency, post-processing
---


title: Generate a 2D distance grid in one pass

text:
# Question
Title: Generate a 2D distance grid in one pass
I'm trying to generate a 2D grid, for use in navigation, where each grid point holds the distance to the nearest obstacle (such as impassable terrain, or a constructed building). So for example, a grid point containing an obstacle would be 0, the grid point next to it would be 1, the next one further away would be 2, etc.

So far I've been able to accomplish this using multiple passes. Each pass, for every grid point, I take the lowest value from all neighbors, and add one. If I want to measure out to a max distance of, say, 10 grid points, I have to make 10 passes, slowly incrementing the most distance grid points.

My question is, is there a way to generate this sort of grid in just a single pass? This grid will be periodically updated during gameplay, and could be very large, so I don't want to be looping over it multiple times if I don't have to.

# Answer
> 2 votes
You can use BFS to accomplish this exactly. You connect all obstacles as nodes (vertices) to the source node. Then simply connect each grid square to the it's neighbors.

You don't actually have to do the connecting. You could simply start with all obstacles in the Queue and keep adding neighbors.

Breadth-First-Search

Time complexity is O ( V + E) so in this case, grid squares plus grid edged = grid squares * 5.

Pseudo code:

```
  // First loop over array2d
 // and register that the distance on tiles with obstacles is 0
  procedure GridBfs(array2d, obstacles)
      create a queue Q
      create a set S //this is a 2d array of areas visited by the algorithm
      enqueue obstacles onto Q
      add obstacles to S
      while Q is not empty loop
         t ← Q.dequeue()
         for all neighbors n of t loop
            if n is not in S then
               add n to S
               enqueue n onto Q
               n->distance = t->distance + 1;
            end if
         end loop
     end loop
     return none
 end BFS

```

This is based on the original BFS code from wikipedia. To get the neighbors, simply look above, beloow and to the left and right of `t` and you'll get all neighboring tiles, represented each by `n` in the algorithm.

# Answer
> 4 votes
Yes, as Arthur Wulf White writes, Breadth First Search is what you want. I wrote a quick & dirty **interactive demo** showing how BFS expands out from each of your obstacles to assign distances.

---
Tags: grid
---


# Question
Title: How can I implement beam effects like these?
I am interested in the techniques I could use to create the following effects:

Can I accomplish this with a particle system or a series of texture quads, or what?

You can see this effects in action here in this video.

# Answer
I think *Polyboards* would be the thing for you. If you can get yourself a copy of Mathematics for 3D Game Programming and Computer Graphics, there is a section dedicated to this technique in the book.
> 2 votes

---
Tags: opengl, particles
---


title: Camera movement bug

text:
# Question
Title: Camera movement bug
In my game, the player's movement script and the camera's movement script are separate.
Both of them use "W", "A", "S", and "D" to move. The camera can also use "Q" and "E" to rotate around the player.

```
transform.RotateAround(player.transform.position, Vector3.up, 2f);   //or -2f

```

The player can use a skill where the animation and the movement are separate. For this, I use the following code to move:

```
public IEnumerator movement() {
    for(int i = 0; i < 66; i++) {        //animation length is 0.67second
        yield return new WaitForSeconds(0.01f);
        controller.Move(this.transform.forward * 0.03f);
        Camera.main.GetComponent<cameraControl2>().followplayerskill();
    }
}

```

When it moves, the camera should also move along with the player, which I have tried:

```
public void followplayerskill() {
    float tempxoffset=xoffset;
    float tempyoffset=yoffset;
    float tempzoffset=zoffset;

    this.transform.position = player.transform.position + new Vector3(tempxoffset, tempyoffset, tempzoffset);
}

```

It works if the camera does not rotate,
but once I press "Q" or "E" to rotate the camera before using the skills, the camera does not move as I would expect, which is shown in this video:
how can I correct it so that the camera can move correctly?

# Answer
From what I can fetch of what you've said, you're using unity with a Transform object which contains a rotate and a translate.

I'm not familiar with unity but here goes:

The documentation does not state what happens if you set a rotate and a translate on the same transform. But you could specify explicitly what to do by adding children transforms: first set the *translation* as the parent, then the *rotation* as the children transform.

You have to make sure that the rotation is always made after the translation.
> 0 votes

# Answer
It looks like your x,y,zoffset variables are set up for the camera in its default position (say, "South" of the player), and don't update when the camera is turned (say, to put the camera "West" of the player) - so when you perform the skill, the camera teleports back to its initial ("South") offset, which puts the player off-screen to its left.

I may be misreading, but it looks like for everything other than the skill, you're tracking positions for the camera and player independently, counting on the fact that moving them by the same offsets should keep them in synch.

The trouble with this approach is that any glitch in your code, rounding error, or unexpected physics interaction, can cause the two to diverge from your desired relative positions, and they have no means to correct this divergence.

A better approach is often to have the camera keep track of a desired offset from the player (often in spherical/cylindrical coordinates) and in each timestep re-calculate its position using the player's (possibly with some smoothing applied).

Your rotation/zoom functions then never actually move the camera - they just update the relative offset coordinates, which automatically gets picked up when the camera is positioned.

Here's a crude example - not best practice by any means, but it should prevent the camera from coming unglued from the character at any time:

```
GameCamera.RotateCamera(float angularRate)
{
   cameraYaw += angularRate * Time.deltaTime;
}

 // moving the camera in "Update" in Unity can cause judder when combined with certain smoothing techniques.
GameCamera.FixedUpdate()
{
   // Compute world offset vector from relative offset in cylindrical coordinates:
   Vector3 cameraOffset = Quaternion.AngleAxis(cameraYaw, Vector3.up) * Vector3.back;
   cameraOffset *= followDistance;
   cameraOffset += Vector3.up * cameraHeight;

   // You can lerp from the old position to the new to make the camera smoother.
   transform.position = playerAvatar.transform.position + cameraOffset;
   transform.LookAt(playerAvatar.transform);
}

```

This shouldn't need any special handling for the player's skill - wherever the player goes, the camera will follow.
> 0 votes

---
Tags: camera, movement
---


# Question
Title: JBullet - Detecting when 2 objects collide?
How can I detect when 2 collision objects collide with JBullet? Currently, all body types are going to be of type RigidBody. I have quite literally been trying to find the answer of this for over 2 months, and would highly appreciate it if someone could help me.

There is some random stuff about collision callback, but that never seems to work - Either there is missing classes, or the code just does not do what I want it to do (Or is something stupid like "check every singke collision object" to do this), and just other things that mean I have never got an answer to my question.

I need to know this to allow ships and a cannonballs to be able to collide and explode. The game is fully playable and has got collision detection manually implemented, however it takes up over 50% of my I7's CPU - Far too much.

Thank you if you can answer my question.

P.S. JBullet is being used on my server, not my client.

# Answer
Collision callbacks are explained in http://www.bulletphysics.org/mediawiki-1.5.8/index.php?title=Collision\_Callbacks\_and\_Triggers. This translates quite straightforward to JBullet. However if you have already tried and failed to follow that, I'll just provide the code I have been using myself.

First set-up a callback that is called on every physics iteration:

```
dynamicsWorld.setInternalTickCallback(new InternalTickCallback() {
    @Override
    public void internalTick(DynamicsWorld dynamicsWorld, float timeStep) {
        // Add your collision checks or other functionality here.
    }
}, null);

```

To detect collisions, you need to iterate all collision contacts in your internalTick callback:

```
Dispatcher dispatcher = dynamicsWorld.getDispatcher();
int manifoldCount = dispatcher.getNumManifolds();
for (int i = 0; i < manifoldCount; i++) {
    PersistentManifold manifold = dispatcher.getManifoldByIndexInternal(i);
    // The following two lines are optional.
    RigidBody object1 = (RigidBody)manifold.getBody0();
    RigidBody object2 = (RigidBody)manifold.getBody1();
    MyPhysicsObject physicsObject1 = (MyPhysicsObject)object1.getUserPointer();
    MyPhysicsObject physicsObject2 = (MyPhysicsObject)object2.getUserPointer();
    boolean hit = false;
    Vector3f normal = null;
    for (int j = 0; j < manifold.getNumContacts(); j++) {
        ManifoldPoint contactPoint = manifold.getContactPoint(j);
        if (contactPoint.getDistance() < 0.0f) {
            hit = true;
            normal = contactPoint.normalWorldOnB;
            break;
        }
    }
    if (hit) {
        // Collision happened between physicsObject1 and physicsObject2. Collision normal is in variable 'normal'.
    }
}

```

I have specified my own object pointer for each JBullet RigidBody using `CollisionObject.setUserPointer()`. In the collision callback I can then compare the objects with `MyPhysicsObject physicsObject1 = (MyPhysicsObject)object1.getUserPointer();`
> 3 votes

---
Tags: java, collision-detection
---


# Question
Title: Do I really need to clear the renderer every iteration?
Just a quick question about fine-tuning/optimization. If I'm making a 2D platformer with a parallax-scrolling background (meaning no two frames are the same) do I really need to clear my renderer for every iteration? The entire scene will be drawn-over anyways, so if I can get rid of one extra function every iteration, it could help to speed things up a little bit, though I realize that render-clearing is not a very expensive function. By the way, I'm using SDL2.

# Answer
On tile based GPUs (commonly seen in mobile hardware) it is beneficial to clear the renderer, as it allows the GPU to dispose of the existing cached frame data.

Here's a quote from OpenGL Insights, dealing with the benefits of clearing the framebuffer on a tile based renderer:

"On a tile-based architecture, avoiding clears can be disasterous for performance: since the frame is built up in frame data, clearing all buffers will simply free up the existing frame data. In other words, not only is glClear very cheap, it actually improves performance by allowing unneeded frame data to be discarded."
> 9 votes

# Answer
**No** you don't *need* to.

As you said yourself, if you whole scene is drawn-over by the new rendered frame, then it makes no visual difference.

And as comments rightfully mentionned, it might have a positive *or* a negative impact on performance: **profile on your target platform(s) to make your decision**.

In the old days, it was common place to actually re-render only the parts of the frame buffer that required a change and keep the "old pixels" around to avoid costly clears. But today this is usually no longer a bottleneck.
> 4 votes

---
Tags: c++, graphics, sdl
---


title: SharpDX.Toolkit setting constant buffer

text:
# Question
Title: SharpDX.Toolkit setting constant buffer
I am trying to use a constant buffer in a program using SharpDX.Toolkit. I use the Toolkit because it has nice font support for writing on the screen.

The problem I face is in assigning data to the constant buffer.

In the screen below you may see a debug of my code. When it comes to the **Draw** event the buffer gets empty (**obj:9** is active) and in **Geometry Shader** all values are **0.0f**. On event **76** \- **GSSetShader** the **obj:16** is active, which contains the data I want to use, non-zero values. I have no idea why it gets overwritten/cleared. I tried assigning or updating buffer in numerous places in the draw method, but none of them helped. For sure it is not a problem of a slot, as in the debug window both (populated and empty) buffers are in **slot 0**.

**NOTE:** this way of loading data to constant buffer worked before I switched to using Toolkit, but then the device was explicitly created with SwapChain. I am not so experienced to tell if it may make any difference.

In my effect file I have defined the buffer as

```
cbuffer ConstantBuffer : register(b0)
{
    float slideX;
    float sinPi075;
    float cosPi075;
    float scaleK;
}

```

and in the main program

```
[StructLayout(LayoutKind.Explicit, Size = 16)]
struct GS_CONSTANT_BUF_DATA
{
    [FieldOffset(0)]
    public float slideX;
    [FieldOffset(4)]
    public float sinPi075;
    [FieldOffset(8)]
    public float cosPi075;
    [FieldOffset(12)]
    public float scaleK;
};

```

followed by

```
private SharpDX.Direct3D11.Buffer _constantBuffer;
private GS_CONSTANT_BUF_DATA constData;
private int sizeOfconstData;
private SharpDX.Direct3D11.Device _device;
private void InitializeConstantBuffer()
{
    System.Diagnostics.Debug.WriteLine("InitializeConstantBuffer");
    constData = new GS_CONSTANT_BUF_DATA
    {
        slideX = 0.0f,
        sinPi075 = (float)Math.Sin(Math.PI * 0.75),
        cosPi075 = (float)Math.Cos(Math.PI * 0.75),
        scaleK = 0.003f
    };
    _device = (SharpDX.Direct3D11.Device)GraphicsDevice.MainDevice;
    sizeOfconstData = Utilities.SizeOf<GS_CONSTANT_BUF_DATA>();
    _constantBuffer = new SharpDX.Direct3D11.Buffer(
                                       _device
                                     , sizeOfconstData
                                     , ResourceUsage.Default
                                     , BindFlags.ConstantBuffer
                                     , CpuAccessFlags.None
                                     , ResourceOptionFlags.None
                                     , 0);
    _device.ImmediateContext.GeometryShader.SetConstantBuffer(0, _constantBuffer);
    _device.ImmediateContext.UpdateSubresource(ref constData, _constantBuffer);
}

```

Draw method in the main program

```
  protected override void Draw(GameTime gameTime)
    {
 GraphicsDevice.Clear(Color.CornflowerBlue);
 for (int i = 0; i < technique.Passes.Count; ++i)
    {
     _device.ImmediateContext.GeometryShader.SetConstantBuffer(0, _constantBuffer);
    _chartGeometry.Draw(
                        GraphicsDevice
                      , SharpDX.Toolkit.Graphics.PrimitiveType.LineList
                      , technique.Passes[i]);
    }
}

```

And the **Draw** method associated with **\_chartGeometry**

```
 public void Draw(GraphicsDevice graphicsDevice, PrimitiveType primitiveType, EffectPass pass)
    {
        if (pass != null)
            pass.Apply();

        // Setup the Vertex Buffer
        graphicsDevice.SetVertexBuffer(0, vertexBuffer);

        // Setup the Vertex Buffer Input layout
        graphicsDevice.SetVertexInputLayout(InputLayout);

        graphicsDevice.Draw(primitiveType, 4, 0);
    }

```

I have also tried changing buffer to dynamic, and hence, changing **UpdateSubresource** to **Map/Unmap**. The result is the same, see creen below, this time **obj:16** (has data) and **obj:8** (does not).

and while debuging **GeometryShader** locals show

# Answer
When using an Effect in the Toolkit (which is similar to the XNA Effect or the native D3D11 Effect API), you are not suppose to access directly the constant buffer but instead setting parameters directly on the effect:

```
_effect.Parameters["slideX"].SetValue(0.0f);
_effect.Parameters["sinPi075"].SetValue((float)Math.Sin(Math.PI * 0.75));
_effect.Parameters["cosPi075"].SetValue((float)Math.Cos(Math.PI * 0.75));
_effect.Parameters["scaleK"].SetValue(0.003f);
_effect.Apply();

```

The effect is automatically managing to update the constant buffer, upload it if it changes since last apply...etc. Though you can still update the constant buffer directly as you did.
> 3 votes

# Answer
After investingating the source of the SharpDX.Toolkit I found out that all contant buffers are cleared if they are not dirty. So, the solution was to create a constant buffer on the effect, and make it dirty, see code below.

```
compiledEffect = (new EffectCompiler()).CompileFromFile(
                                 @"Content\MiniTri - Copy.fx"
                                 , EffectCompilerFlags.Debug
                                  |EffectCompilerFlags.SkipOptimization
                                  |EffectCompilerFlags.WarningsAreErrors
                                 );
_effect = new Effect(GraphicsDevice, compiledEffect.EffectData);

constData = new GS_CONSTANT_BUF_DATA
{
    slideX = 0.0f,
    sinPi075 = (float)Math.Sin(Math.PI * 0.75),
    cosPi075 = (float)Math.Cos(Math.PI * 0.75),
    scaleK = 0.003f
};

_effect.ConstantBuffers[0].Set<GS_CONSTANT_BUF_DATA>(0, constData);
_effect.ConstantBuffers[0].IsDirty = true;

```
> 0 votes

---
Tags: c#, directx, sharpdx
---


# Question
Title: How can I put my game on an NES cartridge?
How can I create an NES cartridge? Is there any tutorial? I need to put a game that runs in an emulator and put it on a cartridge. How to do that? Is this possible from scratch? Or at least could I use an existing cartridge and overwrite the content there?

# Answer
> 8 votes
You need to ensure your game will run properly on the NES hardware. With many 8 and 16 bit consoles, there are limited times you can access the hardware registers. Accessing registers outside the allowed time often results in the program not displaying any output. One emulator to consider is no$nes, another is fceux. The no$nes will warn you if you violate many of the rules. The fceux emulator is probably more accurate but will fail silently if you violate the rules.

The next, or possibly first, thing is to determine which mapper mode you will support. This basically determines how rom or ram are mapped into the CPU and PPU (graphics chip) space, the number of memory banks available, and how the scrolling tilemap will be repeated. When you're ready for the technical details, check out the Comprehensive NES Mapper Document. It's quite technical, but is required knowledge in developing a NES cartridge.

The final step is getting it on the cartridge. There are a few options, one is the INL-ROM NES board, which can be purchased with a flash rom for easier testing. Once your game is running, you can buy the same board and program and solder your own EPROMS into the board.

If you're really interested in NES development, visit the NesDev forums.

I developed a game, called Frog Feast, that ran on the SNES, Genesis, Atari Jaguar, and Neo Geo. A friend created physical versions from old game boards.

# Answer
> 8 votes
Many (especially older) cartridge-based consoles have homebrew development subcultures that have built CompactFlash-based cartridges that you can purchase, load up with your home-brew ROM, and insert into a (usually modded) system.

For the NES, the most popular option seems to be the PowerPak from RetroZone. It does not appear to require a modded NES, since the lockout chip for the system has been circumvented.

You could, of course, also build such a cartridge entirely yourself if you had the requisite engineering knowledge and equipment. But buying one is probably much easier.

---
Tags: modding, roms
---


# Question
Title: What are the limitations of retro consoles?
I'm interested in creating a retro look for a game, and I'm currently in the process of deciding just *how* retro (which generation/console). What would make it easier would be if there was some sort of wiki/document on the limitations of each console, such as maximum number of colours total, maximum per sprite, number of layers, max tiles, max tile size, sprite size, etc., etc.. Take the Game Boy for example. 4 colours, yes, and I can find the screen resolution too. But what about all the other limitations?

So if anyone knows any good resources, it would be a huge help. I find that the freedom that today's generation of computers and consoles provides is a little *too much*, in that I can just keep adding more and more to it, and I'll never finish. I'd love to set a limit, and do the best I can within that limit.

# Answer
> 2 votes
Most of these details are implicit in the hardware specifications for the consoles and the design of their hardware interaction APIs. This information is typically available in the programming guides for the relevant consoles, however those guides are under NDA and the closest you will be able to get is through documentation made available by reverse-engineering (itself a bit of a legal grey area) -- these discuss things like RAM bank count and size, the latency involved in bank-switching and when you can do it (for example, during a vertical retrace blank or not), et cetera.

Fortunately the limitations you seem to be after are some of the more obvious, graphics-related ones. For example, a common limitation of early consoles like the GameBoy and NES was that they supported a fixed (small) number of sprites per line -- the hardware would only blit so many, and if you had too many they just vanished. This would manifest itself as "flickering" of some sprites on the screen when the game view got crowded.

Some of the few resources available include the NESDev wiki, this article on sprites on Wikipedia (which includes statistics on the various capabilities of older hardware-based sprite systems like the GameBoy, NES, et cetera).

# Answer
> 1 votes
Consoles usually has a lot of different modes, for example the DS can have 4 colours, 16 or 256 (maybe even 16-bits, I don't remember). Those were used because of cartridge memory footprint (a smaller game costed less to fabricate), of blit speed and memory footprint.

There were also a lot of techniques like the scanline interrupt, to overcome those limitations (number of sprites included).

As it seems you want to go for looks, just check out graphics from old games and pick your choice, then check resolution and colour depth of that particular game and go for it.

# Answer
> 0 votes
Using the SNES as an example:

8x8 or 16x16 pixel tiles are limited to 16 colors each. The colors may come from one of eight palettes. The tilemaps, containing these tiles, are limited to either 256x256, 512x256, or 256x512 pixels. Within the tilemap, you can use the same tile with a different palette. There was also support for 2 or 4 color background layers to reduce the memory used by the tiles.

The SNES had up to four tilemap layers, depending on the graphics mode used. The display order of the tilemap could be controlled in software.

Sprites are limited to power of two combinations from 8x8 to 64x64. (ie 8x8, 8x16, 32x64 64x64, etc.). Each sprite is limited to 16 colors from a separate set of eight palettes.

One of the neat features of the SNES (and many other 16 bit consoles), is the ability to change display properties per scanline. The background color could be changed, or the tilemap scrolled left or right on each scanline. This is used to create a gradient sky without violating the 16 color limit, or create a wavy image.

I applied the above limitations to my MIT licensed Super Play game engine.

---
Tags: console
---


# Question
Title: Multiple collisions with single texture in XNA
I am developing a game where I want to implement two or multiple time collision with single object.i mean if two bullets collide to a ship then only it will explode...

If a two bullet rectangles intersect with a single ship then ,ship will explode..Here is my collision code..

```
foreach (Enemy e in this.em.Enemies)
                {
                    if (e.boundingRectangle.Intersects(missiles[i].boundingRectangle))
                    {
                        shipHit = true;
                        pos = new Vector2(e.position.X, e.position.Y);
                        e.OnHit();

                        missiles[i].IsActive = false;
                        //count++;

                    }
                    //if (count == 2)
                    //{

                    //    break;
                    //}

                }

                }

```

please helpppppp.....

# Answer
> 1 votes
If by your question you mean that a ship has to be hit twice (or multiple times) before exploding, simply give your ships hit points. Whenever a bullet collides, remove the bullet and decrement the hit point value.

When the hit points reach zero (or less), blow up the ship.

If, however, you mean that a ship explodes if, and only if two bullets collide with it at the same time, simply reset the ship's hit points back to maximum every time you have checked for all of the collisions.

---
Tags: xna
---


# Question
Title: Why don't game developers release their source code?
I was wondering why don't developers of AAA games release their source codes after their game has sold out and support is long gone?

Of course there is this list, where you can find a lot of AAA games with available source code.

I just don't seem to understand why don't other companies do this with their old games? They certainly don't support it any more, and sales are negligible. I am not even sure, if releasing the source would negatively impact a games sells.

I am sure a lot of games, that are doomed by gamespy's closure, could be saved by the community, had their source codes been released.

# Answer
> 57 votes
The short answer is because it's usually a legal minefield, and there's usually little or no return on the investment a company would need to put in to the effort.

The source code and assets of a game are intellectual property. It isn't always true that *all* of the source code and assets are the property of a *single* development studio. For example, the studio may have licensed source code to some engine and made modifications to that code.

That means that the studio would need to identify and remove any source code or assets they do not have the license to redistribute or re-release. Similarly, they would need to vet the entire code base for references to trade secrets or other concepts that they are still bound by legal agreements to keep secret or contained. They'd probably want to scrape the source code for potentially offensive comments or references that may reflect poorly on the company.

That's a lot of work for a non-trivial code base, and that's still only presuming the legal ownership of the code is clear. In many cases with these sorts of games, the original IP holder is out of business or otherwise dissolved, and then you have the mess of who owns what of the remnants of the studio. This can be an extremely complex legal mess depending on how the studio went under and what the initial incorporation agreements were.

Given that, in these contexts, the games in question are usually no longer popular, it's unlikely a studio (or the postmortem IP holder) would see any kind of return on the investment necessary to clean up and solve all the legal and other issues with the code. Failure to *properly* vet all the outstanding intellectual property legalities in a source code release could result in the IP holder of some violated property filing a lawsuit or taking other legal action against the company, as well.

Of course, all that being said, there's another quite common reason that's relatively orthogonal to the legal issues: they just don't *want* to. Maybe they don't care, maybe they are hoping to re-use some of the code later in a re-vitalization of the original game, et cetera. It's their IP, they can choose how to distribute it. Or whether to distribute it at all.

# Answer
> 24 votes
One aspect that hasn't been mentioned before regarding legal issues are software patents.

With a lot of crazy simple stuff out there that's patented, companies may be afraid of publishing the source code in case someone will find out that the game they made millions of has violated a couple hundred (frivolous) patents, and suddenly they're flooded with lawsuits.. which can be expensive even if you "win".

(As far as I know, this hasn't happened with released game source code so far, but I would be surprised if IP trolls weren't mining all the source code Microsoft has opened for various software patent violations..)

# Answer
> 6 votes
On top of what Josh Petrie said, there's also the matter of getting something to work properly.

One such example that I can remember is when the source code for Penumbra was released. Big github repository made public for the Humble Bundle support. It had build notes and all the necessary libraries to build it. However it still took most people several days before they could get it to properly build.

You would be surprised just what a few years can do. APIs change for 3rd party libs, and many things are no longer valid documentation-wise. Angelscript was a big problem for Penumbra because the API changes between versions were huge.

The other big issue is that there's rarely any worth to publishing the source code to a big game. Especially if a company puts a fairly restrictive license on assets and the engine, this poses a big problem for the people interested in the code. This is to protect the works of the developers typically, but many open-source games like that will restrict anyone from making a commercial game off their old code.

So then the open-source game becomes a possible learning experience at best. I don't know about a lot of engines, but most of the open-source ones I've seen are not the best examples. They work because many people put thousands of hours into them. However many games and engines like that tend to be hack-ish, and made for a very specific purpose that tends to not be helpful for budding developers.

Even if someone got their hands on the Source engine source code for example, it wouldn't be terribly helpful if they wanted to apply that to their own project. They would simply be overwhelmed.

---
Tags: source-code
---


# Question
Title: OpenGL: glRotatef cause performance drop while rotating -x and -y
I have made a rotating cube and I got some performance drops while using two glRotatef calls. So basically this code is giving me 80FPS:

```
    //code 1
GLrotate_x += 0.4f;
GLrotate_y += 0.4f;
        glPushMatrix();
            glRotatef( GLrotate_y, 0.0f, 1.0f, 0.0f );
            glRotatef( GLrotate_x, 1.0f, 0.0f, 0.0f );
            glTranslatef(multiplxGL+0.5f+spaceGL/2, -multiplyGL-0.5f-spaceGL/2,  multiplzGL+0.5f+spaceGL/2);
            glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
        glPopMatrix();

```

While this one is giving me 100FPS

```
    //code 2
GLrotate_y += 0.4f;
        glPushMatrix();
            glRotatef( GLrotate_y, 1.0f, 1.0f, 0.0f );
            glTranslatef(multiplxGL+0.5f+spaceGL/2, -multiplyGL-0.5f-spaceGL/2,  multiplzGL+0.5f+spaceGL/2);
            glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
        glPopMatrix();

```

The rotate results from the rotation `code 1` and `code 2` are not the same (cube rotates different).I know that the `code 1` is the most proper way here for the rotation but why the performance drops? Any chance of updating my `code 1` to the performance of `code 2`?

On the other side in DirectX I use:

```
D3DXMatrixRotationYawPitchRoll(&matDXRotate,
                                D3DXToRadian(DXrotate_y),
                                D3DXToRadian(DXrotate_x),
                                D3DXToRadian(0.0f));

```

and then

```
matDXStack->Push();
        D3DXMatrixTranslation(&matDXmove, multiplxDX + 0.5f + spaceDX / 2, multiplyDX + 0.5f + spaceDX / 2, multiplzDX + 0.5f + spaceDX / 2);
        matDXStack->LoadMatrix(&(matDXmove*matDXRotate));
        d3ddev->SetTransform(D3DTS_WORLD, matDXStack->GetTop());
        d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 36, 0, 12);
    matDXStack->Pop();

```

Which gives me 100 FPS and rotate results same as `code 1`.

# Answer
> 2 votes
When measuring performance, use frame times, rather than FPS. In your case:

```
1000 ms /  80 FPS => 12.5 msec/frame
1000 ms / 100 FPS => 10.0 msec/frame

```

These are very even FPS numbers, which makes me suspect that they are tied to the display vsync. Have you tried disabling vsync (with a call like `eglSwapInterval`, or setting the Direct3D swap interval?

After confirming that that's not the issue, you could try constructing the OpenGL matrices manually, to see if that's the issue. None of those calculations should take anywhere near 2.5 msec, though.

# Answer
> 2 votes
OpenGL 1.x's built-in matrix operations are notoriously slow, and may even cause pipeline flushes in some cases. To gain performance, translate your gl matrix operations to client-side code (there are several solutions, http://glm.g-truc.net/0.9.5/index.html and http://cmldev.net/ being popular ones).

If you already have a lot of code, you can easily write wrappers that will let you continue using the same-looking code (by simply renaming a couple of functions), for example..

```
matrix active_matrix;
matrix matrix_stack[64];
int matrix_stack_idx = 0;

void mlPushMatrix()
{
    matrix_stack[matrix_stack_idx] = active_matrix;
    matrix_stack_idx++;
    assert(matrix_stack_idx < 64);
}

void mlPopMatrix()
{
    assert(matrix_stack_idx > 0);
    matrix_stack_idx--;
    active_matrix = matrix_stack[matrix_stack_idx];
}

void mlLoadMatrix()
{
    glLoadMatrixf(active_matrix.data());
}

void mlTranslatef(float x, float y, float z)
{
    matrix t;
    matrix_translation(t,x,y,z);
    active_matrix = active_matrix * t;
}

```

# Answer
> 0 votes
Thank you all but I found an other way to do that. I created (or rather copied form this schema) a rotation matrix `RotateMAT[16]`:

```
#define OGLToRadian(degre) ((degre) * (M_PI / 180.0f))
//...

GLvoid ROT(float x, float y, float z) {
  const float cosA = cosf(OGLToRadian(GLrotate_y));
  const float sinA = sinf(OGLToRadian(GLrotate_y));
  float RotateMAT[16] =
  {
          ((x * x) * (1 - cosA)) + cosA,    ((x * y) * (1 - cosA)) - (z * sinA),    ((x * z) * (1 - cosA)) + (y * sinA),    0.0f,
    ((x * y) * (1 - cosA)) + (z * sinA),          ((y * y) * (1 - cosA)) + cosA,    ((y * z) * (1 - cosA)) - (x * sinA),    0.0f,
    ((x * z) * (1 - cosA)) - (y * sinA),    ((y * z) * (1 - cosA)) + (x * sinA),          ((z * z) * (1 - cosA)) + cosA,    0.0f,
                                   0.0f,                                   0.0f,                                   0.0f,    1.0f
  };
  glMultMatrixf(RotateMAT);

```

}

Now with this code I can simply rotate like:

```
ROT( 0.0, -1.0,  0.0);
ROT(-1.0,  0.0,  0.0);

```

That works much faster (+20FPS) than OpenGL's `glRotatef`:

```
glRotatef( GLrotate_y, 0.0f, 1.0f, 0.0f );
glRotatef( GLrotate_x, 1.0f, 0.0f, 0.0f );

```

---
Tags: opengl, 3d, rotation, matrix
---


# Question
Title: Player doesn't jumps in Box2D implementation
Well, i'm trying to learn andEngine. I was able to successfully implement the move functionality for the player. Now, i'm trying to make the player jump using Box2D. I referred few online tutorials to do this but i am not able to make the player jump. Here's my code:

```
public class MyActivity extends BaseGameActivity {
@Override
    public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
            throws Exception {
         scene = new Scene();
        final float centerX = (CAMERA_WIDTH - back.getWidth()) / 2;
        final float centerY = (CAMERA_HEIGHT - this.back.getHeight()) / 2;

        Sprite backgr = new Sprite(centerX, centerY, back,
                this.getVertexBufferObjectManager());
         rcs1 = new Sprite(85, 250, rc1,
                this.getVertexBufferObjectManager());
         rcs2 = new Sprite(195, 240, rc2,
                this.getVertexBufferObjectManager());
         rcs3 = new Sprite(295, 250, rc3,
                this.getVertexBufferObjectManager());

        ans = new AnimatedSprite(86, 245, ttr,
                this.getVertexBufferObjectManager()) {
            @Override
            protected void onManagedUpdate(float pSecondsElapsed) {
                this.setPosition(pX, pY);
                super.onManagedUpdate(pSecondsElapsed);

            }
        };
        pw = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH),
                false);
        final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(2f,0f, 0.9f);
        body = PhysicsFactory.createBoxBody(pw, ans, BodyType.DynamicBody,
                PhysicsFactory.createFixtureDef(0, 0, 0));
        bodyr1 = PhysicsFactory.createBoxBody(pw, rcs1, BodyType.StaticBody,
                objectFixtureDef);
        bodyr2 = PhysicsFactory.createBoxBody(pw, rcs2, BodyType.StaticBody,
                objectFixtureDef);
        bodyr3 = PhysicsFactory.createBoxBody(pw, rcs3, BodyType.StaticBody,
                objectFixtureDef);

        pw.registerPhysicsConnector(new PhysicsConnector(ans, body, true, true));
        scene.attachChild(backgr);
        scene.attachChild(rcs1);
        scene.attachChild(rcs2);
        scene.attachChild(rcs3);
        scene.attachChild(ans);
        pw.setContactListener(this);
        scene.registerUpdateHandler(pw);
        pOnCreateSceneCallback.onCreateSceneFinished(scene);

    }
private void jump() {

            body.setLinearVelocity(new Vector2(body.getLinearVelocity().x, 12));
                }
}

```

Please Help!

# Answer
> 1 votes
First, when are you calling the `jump()` method? Make sure it really gets called, maybe by using a log message. Second, instead of

```
body.setLinearVelocity(new Vector2(body.getLinearVelocity().x, 12));

```

you should do

```
body.setApplyForce(new Vector2(0, 120));

```

Setting a velocity directly is frowned upon and should be done only in a few exceptional cases such as adding a new body to the simulation that has some initial velocity. Otherwise use forces or linear impulses.

Third, what does this code do?

```
    ans = new AnimatedSprite(86, 245, ttr,
            this.getVertexBufferObjectManager()) {
        @Override
        protected void onManagedUpdate(float pSecondsElapsed) {
            this.setPosition(pX, pY);
            super.onManagedUpdate(pSecondsElapsed);

        }
    };

```

It looks to me that you want your animated sprite to be driven by the physics body (you register the connector) but then you are setting its position to some `pX` and `pY`. The physics body might be jumping, but the Sprite is drawn always at \[pX, pY\] due to this code.

---
Tags: java, android, box2d, andengine
---


# Question
Title: How do I support variable screen ratios using AndEngine?
When displaying a background, AndEngine produces black bars above the image on certain devices. How do I support variable screen ratios for different devices using AndEngine?

# Answer
I believe what you're asking is how to get rid of letterboxing, like this:

By default, AndEngine assumes you want some fixed aspect ratio. It then uses letterboxing to handle devices with different display aspect ratios then what you're providing. The advantage is you have certainty about your layout.

There's more than one approach to get rid of them, but here's what I do. The following code takes a fixed height (in this case 320) and adjusts the width based on the aspect ratio of the device.

```
//Pick some value for your height.
float cameraHeight = 320;

//Get the display metrics object.
final DisplayMetrics displayMetrics = new DisplayMetrics();

//Populate it with data about your display.
this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

//Calculate the aspect ratio ofthe device.
float aspectRatio = (float) displayMetrics.widthPixels / (float) displayMetrics.heightPixels;

//Multiply the aspect ratio by the fixed height.
float cameraWidth = Math.round(aspectRatio * CAMERA_HEIGHT);

//Create the camera using those values.
this.mCamera = new Camera(0, 0, cameraWidth, cameraHeight);

```
> 5 votes

# Answer
I used CropResolutionPolicy, a new policy developed and later further extended by members of the AndEngine community. Crop policy is similar to Ratio that comes with the AndEngine, but instead of padding, it scales the scene while keeping aspect ratio to cover the whole screen and crops the overflow.

Crop policy is illustrated on the following image from this website that explains all the AndEngine resolution policies.

*image used with permission of the author*
> 1 votes

---
Tags: android, andengine, resolution, aspect-ratio
---


# Question
Title: How to stop characters running in to each other?
I am new to pygame and am creating a small game in which players can push each other to go outside the given arena to score points.
I have a problem in detecting when characters run in to each other. I have a player sprite and enemy sprite to detect collision (pygame.sprite.spritecollide), but to take any action after that is very tricky and am not able to cover all the possible cases. In most of the examples, it is always an immovable object (wall/maze/tanker etc) on the other end and so it is relatively easy to implement. But, with both characters moving, I am unable to calculate exactly and deal with this. Also, my characters just shouldn't run in to each other but can be close enough - because they'll have to be able to push each other.
Can anyone give pointers to implement this.

# Answer
> 0 votes
You could model this as a perfectly inelastic collision. That means that the players will keep touching each other after the collision.

Suppose you have two players A and B running at each other at the same speed. A is heavier. So when A and B collide A pushes B backwards and keeps touching B. That seems to me realistic enough when we are talking about characters.

Please see the formulas on this wiki page

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


# Question
Title: How to prevent multiple hits from a single attack that lasts multiple frames?
I went through many websites explaining fighting game systems, frames, hitboxes, but I couldn't find the answer so I ask here.

Basically fighting game hitbox system works like this :

1. Player A starts attack (startup frame). \*No hitbox exists yet.
2. Startup frame finishes, Attack frame hitbox collides Player B and B takes damage(active frame) \*Hitbox exists now.
3. Player A performs attack finishing move (recovery frame) \*No hitbox exists now.

What I'm curious about is, on step 2, let's suppose the total number of active frames is 3, so then B will get punched 3 times in a row, which is unconvincing...

Maybe adding some invincibility frames for Player B will solve the problem, but because Player A's active frame counts will vary between moves(normally fighting games have so many attack moves), calculating the right number of invincible frames per moves will be pain (or not? I haven't tried this method yet :P).

I wonder how other fighting (or action) games solve this kind of problem.

# Answer
*Easy solution 1 :* you can mark each attack move with a unique identifier that is regenerated every move, and mark each character with the identifier of last hit received. If during a frame collision the last hit received id matches the attack id, do not count it as a hit. In case there are more than 2 characters, one attack can still hit multiple opponents.

*Easy solution 2 :* Mark each attack with a boolean flag of “effectiveness”, i.e. whether the hit was delivered to someone or not. When a collision occurs, checks if the flag is set. If it is unset, proceed to perform the hit, and set the flag. If the flag is set, just skip the collision. In case there are more than 2 characters, one attack can hit at most one opponent.

*Less easy solution 3 :* If there is a hit, consider the next attack frame to be finishing moves frames, without any hitting box. Can hit multiple opponents, but only at the same frame.
> 2 votes

# Answer
I am also working on a fighting game and I am doing this by having a Move structure which contains different parameters of an attack (or neutral move) including active frames if any. I keep the active frames in a container which I can delete from. Each frame I reset the properties of every hitbox of my character to default, and after that I activate each one of them, which is needed if there is an active frame currently.
If a hit occurs then I remove the current active frame from the Move containing it. I also remove every active frame if my animation finished has ran through it. An active frame can also have a maximum hit count counter which depletes if it hit once and the frame only gets removed if it is depleted.

(This is a method which works for me for the time being, but the game is not fully developed so there may be problems arising from this later (but I hope not))
> 1 votes

---
Tags: game-mechanics, fighting-game
---


# Question
Title: Textures in Unity3D appear with lower quality than in Photoshop
I made game assets that look great in Photoshop, but they look like crap when I import then into Unity and run the game. Why?

# Answer
> 3 votes
Go to your assets window and click on the image. On the inspector, you will see the import resolution. Switch it to 2048 (it is 1024 by default). You can play with the different filter modes too. For example, I'm developing an old-school kind of game with big pixels, so I set the filter mode to "Point", so that sprites don't get shady.

---
Tags: unity
---