# Question
Title: How to crop or mask a sprite to a specific shape in Unity (2D)?
I'm trying to do a procedural 2D terrain generation. I've managed to make the function to generate the points, and I've been testing/debugging by creating the terrain using a 2D polygon collider on an object.

Now that it's done, I want to use this shape to crop a large sprite using the shape so that I obtain the shaped terrain. If I have a square terrain sprite, is there any way to crop the top or mask it to the shape of the polygon collider (or the shape of the function I'm using).

# Answer
I think a sprite is a multipicture where you change the frame you want, it will have an alpha as part of the bitmap... the sprite class isnt really for inanimate ground images.

in unity, colliders i think should be part of a 2d mesh, mesh renderer, and you can apply the bitmap to the mesh.
> 0 votes

---
Tags: 2d, unity, procedural-generation, terrain, masking
---


# Question
Title: smallest distance randomly generated objects
For a project in gamemaker, I'm making a galaxy with several planets in it (about 30), which have random placements (there is a minimum distance between them). After the planet generating, i'm trying to figure out how to calculate the two closest planets for each individual planet, so I can make trade routes between them. So, each planet has two planets that are closest to it, and I'm trying to make an array in which the coordinates of that planet and the two closest planets are.

I'm using the following code:

```
///trade route making
var a1;
var a2;
var R1;
var dist;

//what each kolom is
global.traderoutes[0,0]="x1";
global.traderoutes[1,0]="y1";
global.traderoutes[2,0]="x2";
global.traderoutes[3,0]="y2";

//global.traderoutes coordinates length, +1 everytime a set is added
global.R1=1;

for (i=1;i=global.TT;i+=1){

  global.a1=100000000; //a1 and a2 are values to check against, larger than any distance could possibly be.
  global.a2=100000000;
for (j=1+i;j=global.TT;j+=1){
    dist=point_distance(global.planetinfo[1,i],global.planetinfo[2,i],global.planetinfo[1,j],global.planetinfo[2,j]);
    if (dist<=global.a1){
       global.traderoutes[0,R1]=global.planetinfo[1,i];
       global.traderoutes[1,R1]=global.planetinfo[2,i];
       global.traderoutes[2,R1]=global.planetinfo[1,j];
       global.traderoutes[3,R1]=global.planetinfo[2,j];

       global.a1=dist;
       global.R1+=1;
    }
    else if (dist<=global.a2){
       global.traderoutes[0,R1]=global.planetinfo[1,i];
       global.traderoutes[1,R1]=global.planetinfo[2,i];
       global.traderoutes[2,R1]=global.planetinfo[1,j];
       global.traderoutes[3,R1]=global.planetinfo[2,j];

       global.a2=dist;
       global.R1+=1;
    }
}
}

```

global.TT is the length of the planetinfo array, where all the coordinates for each planet are stored in the first (xcoordinate) and second(ycoordinate) column.

However, it doesn't work. global.traderoutes always comes out empty, it doesn't create any new rows beside the 0th one, where "x1, y1,x2,y2" are written above each kolomn. Can anyone see a mistake I made in the code? Any help would be greatly appreciated.

# Answer
> 0 votes
```
for (i=1;i=global.TT;i+=1){

```

`i=global.TT`: isn't that supposed to be `<=` instead?

same here?

```
for (j=1+i;j=global.TT;j+=1)

```

Even if you intend to use the assignment operator in a loop, it makes no sense and should be well commented but it appears that it was not the intention.

---
Tags: game-maker
---


title: How to implement uniform grids

text:
# Question
Title: How to implement uniform grids
Up until now, I implemented all-against-all collision detection in my games. It worked fine.

But I reached a point where implementing this kind of collision detection, makes the game run poorly, because there are two many objects to iterate through and check for collision.

I have searched this site and found something about 'uniform grids'. But I didn't completely understand what it is and how to implement it. Tried to Google it but nothing easy enough to understand came up.

I am a beginner to 2D-game programming. Do you mind trying to explain to uniform-grids, or link me to some good tutorial?

Thanks a lot

# Answer
1. Create a 2d-array with approximately one square cell per the one collide-able object (considering the approximate max amount).
2. Each cell in the 2d-array is a iterate-able container (data structure) of your choosing (list preferably) of collide-able objects with a bounding box that currently overlaps / intersects with that cell. It needs to be updated every frame (if the object moves).
3. You only check for collisions between objects that are in the same cell(s) and you only check once every frame.

See the image, you would check the green ellipse against the green circle cause they are both in (1, 2).
> 3 votes

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


# Question
Title: Can I use the inclinometer and accelerometer on every Windows Phone device?
I want to do a little game that uses the Windows Phone inclinometer to control an object's pitch, roll and yaw. In addition, I need the accelerometer in another project to let an object jump.

Can I use the inclinometer and accelerometer on every Windows Phone device or are there older devices that don't support the inclinometer and accelerometer? Can I use the inclinometer and accelerometer on Windows Tablets like the surface?

# Answer
The short answer is *no*.

The longer answer is that you can (and should) specify the hardware requirements of your application via your application's manifest. You should read the section on MSDN explaining this as well as the available sensor capabilities you can expose. Essentially, you add the appropriate keys from that page to the `<Capabilities>` element of your manifest file:

```
<Capabilities>
  <Capability Name="ID_REQ_GYROSCOPE"/>
</Capabilities>

```

This will allow you to avoid problems when users don't have the required hardware, without having to worry yourself about which specific hardware supports which sensors (especially since that information will certainly change over time).

The battery of sensors available in the Windows Phone API are detailed in the documentation. Currently:

* The accelerometer should always be available.
* The gyroscope and compass sensors are *not* required and may not be present on a given device (it appears they will never be present in WP7 devices).

Further, you can see here that the inclinometer readings are actually derived from other hardware sensors:

> The Inclinometer sensor specifies the yaw, pitch, and roll values of a device and work best with apps that care about how the device is situated in space. Pitch and roll are derived by taking the accelerometer’s gravity vector and by integrating the data from the gyrometer. Yaw is established from magnetometer and gyrometer (similar to compass heading) data.

The magnetometer and gyroscope are optional features, again, which you can specify the need for via your manifest as above.

The Surface should have an accelerometer, gyroscope and compass (as should the successor). The Windows API has a parallel namespace for sensor access.
> 1 votes

---
Tags: c#, windows-phone-7, windows-phone-8
---


# Question
Title: How can I make a character smoothly traverse a list of waypoints?
I want to set up paths for enemy characters in my game to patrol. I'd like to be able to define a list of waypoints and have the enemy follow the path from one point to another, but in a smooth curve.

How can I do this?

# Answer
> 5 votes
If you want to take a precise mathematical approach, what you're looking for is an **interpolation function**.

If you have some random points...

... and you want to interpolate (that is, fill in what goes in between). The first thing you're likely to think of is to draw straight lines:

This is called *linear interpolation*, because the function describing how we interpolate between two points is a linear function; `y = m * x + c` kind of deal.

There's nothing stopping us from using a different function to interpolate. Here's an interpolation with a closed B-spline:

It doesn't go through all the points, because basis B-spline control points only influence the shape of the curve.

Cardinal splines, for example, do pass through all points:

I stole the implementations from D3: This is where you'd find the interpolations defined in the D3 source.

Bezier curves are a reasonably simple subset of B-curves (here are some pretty understandable graphics on how they work) and will give good results too. There are others you may want to use; we even have a list.

# Answer
> 2 votes
The other answers all discuss how to draw lines connecting the waypoints, presumably in order to then make the AI character follow the line. I guess that would work, but I prefer an approach where instead of forcing the AI to follow a drawn line, I simply define how the character moves and then use the waypoints as movement targets.

So in other words the waypoint system tells the AI character "walk toward this point" rather than "stick to this line."

For the simplest implementation of such a system, the path is an array of positions, and when the game starts the AI chooses the first position as it's movement target. Once it reaches that target, it switches to the next point in the array. repeat

The path the character takes will naturally smooth between the waypoints if the character's movement characteristics include turning slowly.

---

(btw if you're wondering what results you get with this technique, the flying puffballs in this demo were implemented in the way I just described)

# Answer
> 1 votes
Take the average of each pair of sequential way-points. Use these as your new start and end point for bezier curves. Use the actual points as control points.

You could also use a weighted average if you only wish to avoid sharp corners.

See this for the complete explanation: How do I generate a smooth random horizontal 2D tunnel?

# Answer
> 1 votes
I found this XNA path editor which does path Catmull-Rom spline calculation for you.

---
Tags: path-finding
---


title: Restarting a game

text:
# Question
Title: Restarting a game
I'm having trouble restarting a 2D game when the user presses the "New Game" button.

**Structure of my game:**

The game has several 'screens': Opening screen, instructions screen, main game screen, and a game-over screen.

Each screen is an instance of a class: `OpeningScreen` class, `GameScreen` class, etc.

There is a class named `Main`. This class has three roles.

* It's the JFrame (the window) of the program.
* It has the main method - first class to run.
* It has a method that change's screens.

When the program starts, this class runs. When it first runs:

1. Creates a new instance of itself (it's a JFrame-type class).
2. Creates an instance of every 'screen-class'. The constructor of each 'screen-class' takes the instance of Main as an argument: (aka: `GameOverScreen gameOverScreen = new GameOver(this)`).
3. Creates a new JPanel named mainPanel, and adds it to the JFrame. Any screen to be displayed will be contained in this JPanel (The screens are also JPanel-type classes).

**How the changeScreen() method works:**

The signature of changeScreen() is this: `changeScreen(JPanel from, JPanel to)`.

Whenever a screen needs to be changed, the current screen that is displayed calls this method, like so: `main.changeScreen(this, main.InstructionsScreen)`. It removes the previous screen from `mainPanel` and adds the new screen to `mainPanel`. As said, these screens are created when the program launches.

This is the method that changes screens:

```
public void changeScreen(JPanel from, JPanel to){

    mainPanel.remove(from);
    mainPanel.add(to);

    mainPanel.revalidate();
    mainPanel.repaint();

}

```

**My problem:**

After a game is finished, the Game class calls the `changeScreen` method: `main.changeScreen(this, main.GameOverScreen)` .

This replaces the game screen with a game over screen. Pressing the "New Game" button in the game-over screen, calls `main.changeScreen(this, main.GameScreen)` .

**The problem:** Pressing the "New Game" button in the game-over screen, indeed displays once again the instance of the `Game` class. But this is the old instance, so the game is not restarted. It's already finished.

I tried to do the following changes in `changeScreen()`:

```
public void changeScreen(JPanel from, JPanel to){

    mainPanel.remove(from);

    if(to.equals(gameScreen)){
        gameScreen = null;
        gameScreen = new GameScreen(this);
    }
    mainPanel.add(gameScreen);

    mainPanel.revalidate();
    mainPanel.repaint();

}

```

This should reset the `gameScreen` object. But this creates a delay of about 10 seconds when pressing the "New Game" button.

What would be a good way of restarting the game?

Thank you

# Answer
> 1 votes
That's an OK way to do it. The way I do is that I have a `ScreenManager` which "*loads*" screens, those screens are implementing the `IScreen` interface and has different methods like `LoadContent`, `UnloadContent` and `Initialize`.

For instance, when I press the PLAY button in the main menu, the `ScreenManager`'s `addScreen` function runs, sets the `oldScreen` variable's value to the `newScreen`'s value(in this example the main menu screen is becoming the `oldScreen`) and creates, loads the new screen whilst "*Unloading*" the previous one. *(Note that I am using a loading screen)*

The when the unloading is done, and the `LoadContent` sets the `ScreenManager`'s state to DONE, the `ScreenManager` is waiting for the user's input (press any key to continue). When it finally gets the input, the `ScreenManager` intializes the `newScreen` and removes the loading graphics.

In my `ScreenManager`, restarting is nothing else but calling the `addScreen` function of my `ScreenManager`.

---
Tags: game-state, screen-management
---


# Question
Title: Restarting a game be resetting an object
In a game I made, I want to restart the game when the players presses a button.

I have an instance of a `Game` class, which is where most of the game happens.

I though that I could simply initialize it again, and it will be reset.

`Game game = new Game();` \- When the program launches. `game = new Game();` \- When restarting the game.

But the game uses a lot of additional classes, such as `Tank` and `Missile`. Do I have to initialize all of them too, or is initializing the Game class, which will create new `Tank` objects and `Missile` objects (with the same reference names as the previous Game instance), enough?

In general, what would be the best way to reset a game or a level in a game?

Thanks

# Answer
> 0 votes
You already asked a very similar question to this, I have explained a simple ScreenManager's working process in this answer.

When you "unload" your screen, or Game class in your example, then you should remove every item, everything that is related to THAT game class. Storing the objects in Arrays, lists or vectors (depending on language) is (from my point of view) a good practice. It makes handling objects easier and more reachable.

Check my other answer (link above) to see how my simple ScreenManager is working.

---
Tags: 2d, levels
---


# Question
Title: How long does it take for OpenGL to actually update the screen?
I have a simple OpenGL test app in C which draws different things in response to key input. (Mesa 8.0.4, tried with Mesa-EGL and with GLFW, Ubuntu 12.04LTS on a PC with NVIDIA GTX650). The draws are quite simple/fast (rotating triangle type of stuff). My test code does not limit the framerate deliberately in any way, it just looks like this:

```
while (true)
{
    draw();
    swap_buffers();
}

```

I have timed this very carefully, and I find that the time from one `eglSwapBuffers()` (or `glfwSwapBuffers`, same thing) call to the next is ~16.6 milliseconds. The time from after a call to `eglSwapBuffers()` to just before the next call is only a little bit less than that, even though what is drawn is very simple. The time that the swap buffers call takes is well under 1ms.

However, the time from the app changing what it's drawing in response to the key press to the change **actually showing up on screen is \>150ms** (approx 8-9 frames worth). This is measured with a camera recording of the screen and keyboard at 60fps.

Therefore, the questions:

1. Where are draws buffered between a call to swap buffers and actually showing up on screen? Why the delay? It sure looks like the app is drawing many frames ahead of the screen at all times.
2. What can an OpenGL application do to cause an immediate draw to screen? (ie: no buffering, just block until draw is complete; I don't need high throughput, I do need low latency)
3. What can an application do to make the above immediate draw happen as fast as possible?
4. How can an application know what is actually on screen right now? (Or, how long/how many frames the current buffering delay is?)

# Answer
Any drawing API function called from the CPU will be submitted to the GPU command ring buffer to be executed later by the GPU. This means that OpenGL functions are mostly non-blocking functions. So the CPU and the GPU will be working in parallel.

The most important thing to note is that your application can be CPU or GPU bound. once you call glFinish the CPU should will wait the GPU to complete it's drawing commands, if the GPU is taking more time and may/is causing the CPU to stall then your applications is GPU bound. If the GPU finishes it drawing commands and the CPU is taking too long to glFinish then your application is CPU bound.

And note that there is a difference between `glFlush` and `glFinish`.

`glFlush`:indicates that all commands that have previously been sent to the GL must complete in finite time.

`glFinish`: forces all previous GL commands to complete. Finish does not return until all effects from previously issued commands on GL client and server state and the framebuffer are fully realized."

glXSwapBuffers performs an implicit glFlush before it returns. Subsequent OpenGL commands may be issued immediately after calling glXSwapBuffers, but are not executed until the buffer exchange is completed.

The actual frame time will most likely be determined by which of the two CPU/GPU is taking more time to complete its work.
> 8 votes

# Answer
OpenGL never updates the screen, technically.

There is a window system API that is separate from GL (e.g. GLX, WGL, CGL, EGL) that does this. Buffer swaps using these APIs generally implicitly invoke `glFlush (...)` but in some implementations (e.g. the GDI rasterizer on Windows) it does a full `glFinish (...)`:

<sup>\*On the left side, is the ICD (hardware) path through `SwapBuffers (...)`. On the right side, the GDI (software) path.</sup>

If you have VSYNC enabled and double-buffering, then any command that would modify the back buffer before a pending swap occurs ***must*** stall until the swap. There is a limited depth to the command queue, so this stalled command will eventually cause a traffic jam in the pipeline. This could mean that instead of blocking on `SwapBuffers (...)` your application actually blocks on some unrelated GL command until VBLANK rolls around. What it really boils down to is how many back buffers you have in your swap chain.

As long as all of the back buffers are full of finished frames yet to be moved to the front, swap buffers will implicitly cause blocking. Sadly, there is no way to explicitly control the number of back buffers used by most GL window system APIs (aside from **0** single-buffered or **1** double-buffered). The driver is free to use **2** back buffers if it wants (triple buffering), but you cannot request this at the application level using something like GLX or WGL.
> 5 votes

# Answer
I assume you're familiar with this experiment?

Essentially John Carmack was doing something similar, recording the screen and timing pixels sent to the screen. He found that a good deal of the latency came from the screen. Other factors were the input delay from the keyboard, video drivers and or course the execution of the program itself.
> 1 votes

---
Tags: opengl, opengl-es, vsync, double-buffering, latency
---


# Question
Title: Tile Based Sprite Collision With Lots of Sprites
I am running into lag when loading many sprites onto the screen. If I have less than 12 on the screen it runs smoothly until I add a couple more and then it bogs down.

I currently have this as my detection code;

```
public void Collision(Sprite sprite, Rectangle newRectangle, bool passable, bool speedRestricted, int xOffset, int yOffset)
        {// Tile boundaries
            if (sprite.Bounds.Top(newRectangle) && passable == false)
            {
                animation.Position = new Vector2(sprite.Position.X, (newRectangle.Y - sprite.Bounds.Height));
            }
            if (sprite.Bounds.Left(newRectangle) && passable == false)
            {
                animation.Position = new Vector2((newRectangle.X - sprite.Bounds.Width), sprite.Position.Y);
            }
            if (sprite.Bounds.Right(newRectangle) && passable == false)
            {
                animation.Position = new Vector2((newRectangle.X + sprite.Bounds.Width), sprite.Position.Y);
            }
            if (sprite.Bounds.Bottom(newRectangle) && passable == false)
            {
                animation.Position = new Vector2(sprite.Position.X, (newRectangle.Y + sprite.Bounds.Height));
            }
}

```

It is called in like this;

```
foreach (var tile in map.CollisionTiles)
        {
            player.Collision(player, tile.Rectangle, tile.Passable, tile.SpeedRestricted, map.Width, map.Height);

            foreach (var sprite in sprites)
            {
                sprite.Collision(sprite, tile.Rectangle, tile.Passable, tile.SpeedRestricted, map.Width, map.Height);
            }
        }

```

Now collision detection works perfectly so I don't have an issue there it's just when there are lots of sprites in my `List<Sprite> sprites` does it lag. If I remove the collision detection from the code I can load thousands of sprites onto the map.

Question: How do I limit the detection area for the sprites so it only compares the tiles around the sprite instead of all the tiles on the map for each sprite.

I have looked through the other questions and found none when it comes to multiple sprite detections for tile maps, just the main player's collision detection.

# Answer
As you said, the problem arises because you're comparing each tile to each sprite. This leads to many unnessesary checks. You can cut down on these checks by only checking the tiles directly around the sprites.

1. Make sure your tiles are stored appropriately. In a multidimensional array, or anywhere where their positional data is stored implicitly.
2. Find the tile each of the corners of your sprite(the red rectangle) is hovering over. In the image these are \[10,3\], \[12,3\], \[10,6\] and \[12,6\].
3. Determine the range of your sprite, using the four tiles from step 2. (The yellow area)
4. Check collisions only for the tiles within the sprites range plus an extra tile on all sides. (The green area)

This way you can cut down on most collision checks, especially when your level size is large.

If your sprite is smaller than your tiles, you can get away with only determining what tile the center of your sprite is over(instead of all corners), because it can only ever collide with the 9 tiles around its center.

Finally, for further improvement, you only have to check the sprites that are moving. If a sprite is not moving, it won't be able to collide with any tiles anyway.

**EDIT:** Step one is important.

**Store your tiles in a multidimensional Array**.

When your tiles are stored in a `List<tile>` is is impossible to find close tiles without looping over everything (as you probably have noticed). An array makes this much easier, because it implicitly stores the locational information of whatever is in it.

Let's say you have a 10 by 10 tilegrid.

`private Tile[,] TileArray = new Tile[10,10];`

You create can create a multidimensional array and place the tiles in the array according to their position. you can now use the information that a tile at tileArray\[5,6\] will always be next to a tile at tileArray\[6,6\].

Combining the array and the fact that we know the tile size, finding the tiles becomes a breeze.

let's say we have a very small Sprite and we want to find the tiles it can collide with. We can start by calculating the Sprites position on the tileArray (Step 2, simplified because the sprite is small). simply by doing the following:

```
int XOnArray = Math.Floor(sprite.X/tile.width);
int YOnArray = Math.Floor(sprite.Y/tile.height);

```

This gives us the X- and Y-coördinates of the sprite on the tileArray. We know it is (for example) currently on tileArray\[4,5\]. We can now check for collision with all the tiles near tileArray\[4,5\] (as per step 4):

```
for(int i=XOnArray-1; i<=XOnArray+1; i++)
{
    for(int j=YOnArray-1; j<=YOnArray+1; j++)
    {
        checkCollision()
    }
}

```

This decreases the collision checks per sprite from all tiles to only nine!

Again, if anything is unclear, let me know, and I'll try to explain it better.
> 1 votes

---
Tags: xna, c#
---


title: Where can I share my game?

text:
# Question
Title: Where can I share my game?
I am looking for places on the web to share my game.

I'm relatively new to game development. Not looking to 'promote' my game or sell it. Just want to share it in places where there is a possibility people will download and play it.

Are there any sites that are meant to share indie games? And in general any site where I can post a download to my game will be great.

Thanks

# Answer
> 6 votes
Here are the sites I hang around:

TIGSource Forums \- Even though it isn't the best community in my opinion, it still is a great way to share your games and get some critical(and sometimes crappy) feedback from other developers.

GameDev Forums \- Another good place to get great feedback on your game. I think you might have more luck here, on the critiscm end than at TIGSource

Kongregate \- Another site which has an awesome community. They also host web games(with monetization opportunities - so it's another great way to get feedback and some monetary reward as well!

GameJolt \- Friendly Developers and Players, even though the developers can become a bit rowdy sometimes. A lot of friendships were made here and again, it's a great place to share your game - even if it is not web-based.

r/GameDev \- Who doesn't like Reddit? ;) Another great way to share and communicate with other developers.

IndieDB \- This is, perhaps, the best way for you to share your game to a large audience of players(and developers - who are secretly disguised as players). The forums are great and they have a nice way of letting people rate your game and leave reviews accordingly!

Our Chatroom \- This site's chat is a really awesome place to be if you want to share your game and get feedback in "realtime". I frequent this myself and it's a great place to share screenshots/builds and get into intense technical discussions. An the occasional tom-foolery/drama/emotional outbreaks. ;)

Indie Game Forums \- As they put it on their web site: *"\[...\] a diverse community has grown out of a passion for creating great games. Here you will find over 10 years of in-depth discussion on game design, the business of game development, and marketing/sales. Indie Gamer also provides a friendly place to meet up with other Developers, Artists, Composers and Writers. "*

Social Networks like Twitter and Facebook are also great ways to share your games. Facebook has a group devoted to game developers. Twitter has a #gamedev hashtag as well as #screenshotsaturday tag if you're looking to get exposure as well as feedback.

Oh, and there's also the IRC channels! I don't IRC too much, but I'd recommend the #reddit-gamedev channel on irc.freenode.net.

---
Tags: distribution
---


# Question
Title: Best (for performance) practices for using texture slots (glActiveTexture)
Where exactly does the cost from switching textures come from? Would it be a good strategy to just fill all available texture slots from 0 to GL\_MAX\_IMAGE\_TEXTURE\_UNITS - 1 using glActiveTexture and glBindTexture to avoid the amount of state changes?

Or is it better to minimize the amount of texture slots that are used at the same time, and rely on sorting by material to keep texture changes for each used slot as low as possible?

Also, seeing as bindless textures are available in OpenGL 4.4+, can it be assumed that they perform better in general, i.e. should I prefer changing the uniform value to point to a new texture over re-binding a texture to a certain texture slot?

# Answer
The 15th of this month at Steam Dev Day nVidia presented this talk.

It explain how to write a modern openGL program to minimize bottleneck and stall. If you have Dx11 hardware they propose as best solution texture array with sparse texture, using one texture array for every type/size of texture.

They also explain other techniques to minimize parameters upload and minimize drawcalls. Luckily Dx11 hardware have become really cheap.
> 1 votes

---
Tags: opengl
---


title: Weird case of a key not working

text:
# Question
Title: Weird case of a key not working
I finished a game in Java. It works perfectly fine on my computer.

Sent it to a friend. On his computer, for some reason, one of the keys that are used to play doesn't work inside the game. (It works in any other context, like a web browser).

He tried pushing this key with no other keys held. Still didn't work. So it's not a 'key combination' issue.

We both use Windows and the most updated JRE version.

What could it be? This is really weird. Thanks

# Answer
> 1 votes
I've had cases where some keys are "coded" differently based on manufacturer and appear differently in Windows. For example, I was setting up a hotkey for an application, and pressing something like \[ came up as "OemSomethingSomething".

If it's an unusual key, maybe your friend's keyboard is sending a key code that Java misinterprets.

---
Tags: keyboard, control
---


title: Reloading Resources on Resume

text:
# Question
Title: Reloading Resources on Resume
I'm having a problem with my game. If I press the "Home button" the game is paused... everythings fine, but if I then go back to the game all the resources are reloaded before I can continue the game. And it takes quite a bit. Is this normal, or is there a way to avoid the reloading?

I have write following code in onResume and onPause method. It loads same texture again and again on resume of game.

```
    @Override
    protected void onPause() {

            super.onPause();
            if (Utility.flagSound && mScene != null) {

                    if (mScene.getUserData().equals(Constants.GAME_SCENE))
                            Utility.isPlayLevelMusic = false;
                    else
                            Utility.isPlayLevelMusic = true;

                    audioManager.gameBgMusic.pause();
                    audioManager.levelBgMusic.pause();
            }

            if (this.mEngine != null && this.mEngine.isRunning()) {
                    this.mEngine.stop();
            }

    }

    @Override
    protected void onResume() {

            super.onResume();
            if (audioManager != null && Utility.flagSound && dataManager != null) {
                    if (Utility.flagSound) {
                            if (Utility.isPlayLevelMusic)
                                    audioManager.levelBgMusic.play();
                            else
                                    audioManager.gameBgMusic.play();
                    }
            }

            if (this.mEngine != null && !this.mEngine.isRunning()) {
                    this.mEngine.start();
            }

    }

```

I would be glad if anybody could help...

# Answer
> 3 votes
This is normal behaviour. It happens because of the Android Activity Lifecycle destroying and recreating the OpenGL context onPause/onResume. From GLSurfaceView documentation:

> **Activity Life-cycle**
>
> A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients are required to call onPause() when the activity pauses and onResume() when the activity resumes. These calls allow GLSurfaceView to pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate the OpenGL display.

Because Android phones work with very limited resources, especially the older and low-end devices, there is not enough memory to hold multiple contexts with all the textures. The easiest way is to unload everything onPause and reload back onResume. This is partly handled by AndEngine and partly by Android.

If this is causing you issues, starting from Android 3.0, you can actually preserve the context. See `setPreserveEGLContextOnPause` for more information. Note that AndEngine might not count with this option and behave unexpectedly. Also note that as of now, about 30% devices still run Android 2.x where this is not available.

# Answer
> 0 votes
Try to modify method onSetContentView() in **BaseGameActivity.java**

with this code

```
protected void onSetContentView() {

    this.mRenderSurfaceView = new RenderSurfaceView(this);
    this.mRenderSurfaceView.setRenderer(this.mEngine, this);
    if(android.os.Build.VERSION.SDK_INT >= 11){
        this.mRenderSurfaceView.setPreserveEGLContextOnPause(true);
    }
    this.setContentView(this.mRenderSurfaceView, BaseGameFragmentActivity.createSurfaceViewLayoutParams());
}

```

---
Tags: android, andengine
---


# Question
Title: How can I find all connected objects of the same type recursively?
In my game, when a user selects an object of some type, I'd like to search for all other objects of the *same* type that are connected to that first one.

For example, if the user selects a object of type 2, I want to check the object next to that one to see if it is also of type 2 and so on in all directions (up, down, left and right, et cetera) until there are no more objects of that type connected.

Does anyone know how I could do something like this? You can assume I have access to the set of connections from any given object.

# Answer
Assuming your objects are stored in a grid (2D or flattened 2D array ), you can use a flood fill like algorithm. Though it will be simpler, as you don't need all the problems and edge cases that come with image processing.

Start with the object that was selected by the user. Check the object to the right if it's the same type if it's not that will be the recursion termination case. Repeate the process for all neighbors. To track the object you can simply pass a vector by refecrence and add any new items (or their indices) to the list. Here is a psudo code:

```
func Floodfill ( int currentIdx, targetObjectType):
  If ( targetObjectType of node != objectType[currentIdx] )
     return;

  Add currentObject to list

  Floodfill (one step to the west of node, targetObjectType);
  Floodfill (one step to the east of node, targetObjectType);
  Floodfill (one step to the north of node, targetObjectType);
  Floodfill (one step to the south of node, targetObjectType);

  return;

```
> 2 votes

# Answer
It sounds like your objects are stored in a grid, but really it doesn't matter so long as you have a list of connections between any given object (which it certainly sounds like you do).

This is the kind of thing like lends itself to a recursive solution. In the most basic case, a click occurs on an object and you want to check all the connected objects, in C#-like pseudo-code (which should be easily translatable):

```
void GetConnectedObjects(Object object, List<Object> results) {
  // Consider the clicked object part of the results, always.
  results.Add(object);

  foreach(connection in object.Connections) {
    if (connection.TargetObject.Type == object.Type) {
      results.Add(connection.TargetObject);
    }
  }
}

```

This simply loops through all the connections of some object, checks their type, and if they match, adds the connected object to the result set (which also always contains the clicked object). You can replace the "connections" loop with a loop that checks adjacent grid X, Y positions if you are using a grid instead; the idea is the same.

Now the next step is to do this *exact same thing* for every connected object that matches. We can adjust the function as so:

```
void GetConnectedObjects(Object object, List<Object> results) {
  // Consider the clicked object part of the results, always.
  results.Add(object);

  foreach(connection in object.Connections) {
    if (connection.TargetObject.Type == object.Type) {
      // Note that we no longer need to explicitly add the target object
      // here, since the function always adds the first parameter to the
      // result set.
      GetConnectedObjects(connection.TargetObject, results);
    }
  }
}

```

This will find *all* connected objects, and might seem like the final solution.

But there is a caveat: consider a graph of connected objects like (`A -> B -> C -> A`) or, on a grid, a 2x2 block of objects of the same type. Because the above solution does not consider if an object has *already been seen*, it can recurse *forever* in such a case. So you need to track that:

```
void GetConnectedObjects(Object object, HashSet<Object> seen, List<Object> results) {
  results.Add(object);
  seen.Add(object);

  foreach(connection in object.Connections) {
    if (connection.TargetObject.Type == object.Type) {
      if (!seen.Contains(connection.TargetObject)) {
        // If we have already seen this connected object, don't
        // traverse it again.
        continue;
      }

      GetConnectedObjects(connection.TargetObject, results);
    }
  }
}

```

That should provide you a basic starting platform. Note that for API usability, I'd recommend making the above function a private implementation detail and instead exposing a cleaner public method:

```
List<Object> GetConnectedObjects(Object object) {
  List<Object> results = new List<Object>();
  HashSet<Object> seen = new HashSet<Object>();
  GetConnectedObjects(object, seen, results);

  return results;
}

```

Remember also that any recursive solution can be written as an iterative one, and iterative solutions can be better in some cases because they do not have stack recursion limits. Although I feel the problem is more naturally explained as a recursive solution, in practice I'd suggest trying your hand at converting it to an iterative one to avoid any limitations you can run into due to stack depth, et cetera. Remember also that the above was pseudocode meant to provide a basic idea of the algorithm and certainly could be more optimally constructed in your specific language
> 0 votes

---
Tags: libgdx, box2d
---


# Question
Title: unable to launch LibGDX Particle Editor.jnlp
I am not able to launch LibGDX ParticleEditor.jnlp file on my system(win7 64 bit) with java7.

when I execute this file with javaws.exe in jre7/bin folder, it displays splash screen of **badlogic games** for jst 2-3 sec but after that it gives an alert having error message "**Unable to launch application**". And the exception is :

```
com.sun.deploy.net.JARSigningException: Found unsigned entry in resource: http://libgdx.googlecode.com/svn/jws/gdx-tools.jar
    at com.sun.javaws.security.SigningInfo.getCommonCodeSignersForJar(Unknown Source)
    at com.sun.javaws.security.SigningInfo.check(Unknown Source)
    at com.sun.javaws.security.JNLPSignedResourcesHelper.checkSignedResourcesHelper(Unknown Source)
    at com.sun.javaws.security.JNLPSignedResourcesHelper.checkSignedResources(Unknown Source)
    at com.sun.javaws.Launcher.prepareResources(Unknown Source)
    at com.sun.javaws.Launcher.prepareAllResources(Unknown Source)
    at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
    at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
    at com.sun.javaws.Launcher.launch(Unknown Source)
    at com.sun.javaws.Main.launchApp(Unknown Source)
    at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
    at com.sun.javaws.Main.access$000(Unknown Source)
    at com.sun.javaws.Main$1.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

```

I've googled this problem,, but still unresolved. Please help me .

# Answer
> 5 votes
I'm guessing you have 64 bit java installed. The ParticleEditor.jnlp fails to run on a 64 bit JRE. What you would want to do is:

1. Download a 32 bit version of JRE. Here is the Oracle link for that: http://www.oracle.com/technetwork/java/javase/downloads/java-se-jre-7-download-432155.html Just make sure you select a "x86" version of the JRE from the list, appropriate for the platform you want to launch the .jnlp file on. (Mac is not supported as far as I know. In case it already is, please correct me.)
2. Assuming you're on Windows, locate the "javaws.exe" file under "C:\Program Files (x86)\Java\jre7\bin" (of course, this is its location on my desktop, the location on yours should be similar). Notice the "C\\:Program Files (x86)" folder - this is where all your x86 (32 bit) stuff goes - as opposed to "C:\Program Files", for 64 bit stuff.
3. Drag and drop your .jnlp file onto the javaws.exe file.

This should solve your issue.

The details of this answer are only here to help anybody who stumbles upon this issue - I was one of them until some time ago :-)

---
Tags: java, libgdx, particles
---


title: How to achieve anisotropic filtering

text:
# Question
Title: How to achieve anisotropic filtering
I am loading a texture and using `glGenerateMipmap()` on it to achieve some level of mipmaping.

I get different result on nVidia gt 555m, and on Intel HD 3000.

The texture rendered by nVidia is not with Anisotropic filtering, and that rendered by intel HD 3k is. How to manually adjust this feature for different GPU?

Also the tiling of the texture is much more apparent on nVidia!!

In the description of glGenerateMipmap() it is specified that the way glGenerateMipmap works is different for different implementations of OpenGL.

Is this something to do with glHint() GL\_FASTEST , GL\_NICEST , and GL\_DONT\_CARE? Or am I better of mipmaping the texture myself?

# Answer
> 9 votes
If you have the EXT\_texture\_filter\_anisotropic extension, you can set the maximum texture anisotropy parameter using glTexParameterf to allow the driver to take more samples during texture filtering.

A code snippet:

```
float aniso = 0.0f;
glBindTexture(GL_TEXTURE_2D, texName);
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &aniso);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso);

```

---
Tags: opengl, textures, glsl, mipmaps
---


# Question
Title: How can I scale the number and challenge of enemies in an attack wave as the game progresses?
I'm currently making a defense game where enemies will spawn and attack the player's army. It's similar to a Tower Defense game, except there is only one level. The enemies will keep spawning until eventually the user dies or he amasses a large enough army that they wipe out any enemy that spawns instantly (hopefully it'll be challenging enough that this won't happen).

What I'm struggling with at the moment is how to make this game get progressively harder and the probability of an enemy spawning basically eventually reach 100%.

So far I've got something similar to the following

```
if(Math.random() < 1 - (1/elapsed_time) && spawnTimer <= 0 ){
    spawnEnemy()
    spawnTimer = rand(); // random number between 1 and 3
}

```

But it seems too uniform to begin with. At the moment I'm only spawning one type of enemy, the idea being that tougher enemies are spawned as time progresses as well.

I also think I need to randomise my `spawnTimer` at bit more and make that get quicker as time progresses, but I just can't seen to get my head around what my logic should really look like for this whole section. Is anyone able to help with a rough idea of this kind of formula?

I'm currently using javascript to write the game, but obviously it's more about the concept.

# Answer
The function you chose is not likely to be suitable for your purpose. First, if you go this route a failed random condition should result in a delay before the next time you roll the dice. Also, it is unlikely that keeping the spawn timer within a constant range good for your goal.

Let `thresh` be a difficulty threshold you think is high. We use that later to decide when to slow down the pace at which the game gets harder.

Let `rate` be the amount of monsters you want coming in every minute (or round).

Let `GROWTH_RATE` be the rate in which difficulty increases (for now it'll be `0.2`).

Let's say you start with `rate = 10`. Now the player killed `5` monsters so you can increase rate by `GROWTH_RATE * 5 = 1.0` and the new `rate = 11`.

How to implement a condition that will generate `rate` monsters every minute:

Set spawn timer to a number between `0.5` to `1.0` `multiplied by 60 seconds or`round-time`and divided by`rate`. Also leave a`0.25\` chance that no monster is spawned when the timer reaches 0 and the time is randomized again.

If `rate` ever reaches `thresh` you need to slow down. Now instead of increasing `rate` by `GROWTH_RATE`, you could increase it by `1 / math.sqrt(rate)`. That way the player won't be destroyed instantly in the harder setting.

You can reset `thresh` to be around 80% of the `rate` at which the player lost the game.

If you wish to randomize the strength of the monster be cautious about the timer. For instance, if you decide that `player-score` (determined by monsters killed so far) will be used to determine the max strength of a monster that could spawn, you can do something like this: `max-monster-strength = player-score / 1000`. Then randomize a `float` or `double` between `0.0` to `1.0` and multiply the result by itself.

```
float monster_power = Math.random();
monster_power *= monster_power; // Multiply result by itself
    // Makes hard monsters less frequent than weak ones
monster_power *= max_monster_strength;

```

Now when you randomize the timer you should probably take the power level into account. For instance you could multiply the timer result by the square root of the next monsters power.

```
spawn_timer *= math.sqrt(monster_power);

```
> 3 votes

# Answer
There's lots of options, two with your current setup:

* Make enemies harder
* Spawn more enemies (either more often or multiple at a time)

Then more with additional features:

* Enemies start dealing different types of damage, and the player must defend differently against each. For example, ranged attacks, magic, etc.
* Enemies start defending themselves against different types of damage. The player must build multiple types of damage dealing devices to counter. For example, player starts with arrow attacks and cannonball attacks. An enemy that has a very high resistance to arrows spawns, so the player must make sure they've balanced their attacks.

As for making a difficulty curve, there's really no correct answer. It's going to take a lot of playtesting and tweaking to get it right. It'll depend on how long the game is supposed to last and how difficult you want it to be. I suggest you use Excel or a site like WolframAlpha and see what kind of curve different functions create. Try exponential increases, linear increases, etc. Find one that works for you.
> 6 votes

# Answer
Instead of having a fixed number of enemies (one) spawn with a variable probability, you could turn it around and have a variable number of enemies spawn with a fixed probability.

```
static const double SPAWN_CHANCE_ON_DIFFICULTY_1 = 0.01;

for (int i = 0; i < currentDifficulty; i++) {
   if(Math.random() < SPAWN_CHANCE_ON_DIFFICULTY_1 ){
       spawnEnemy()
   }
}

```

On difficulty level 1, this will have a 1% chance to spawn one enemy per tick.

On difficulty level 1000, it will spawn up to 1000 enemies, each one with a separate chance of 1%. This means that on average 10 will spawn per tick, but it could also be more or less. There is a possibility that a number very different from 10 will spawn at once, maybe even all 1000. but that's a very unlikely event due to how probability works (compare: Law of Large Numbers).

When you add more different enemies with different behaviors and stats, you maybe want some of the tougher enemies to only start spawning on higher difficulties and even then with a low density at first. To do this you could add a difficulty-modifier which is subtracted from the current difficulty. That way the enemy won't spawn before that difficulty-level is reached and even then only with a lower chance at first:

```
for (EnemyType enemyType: allEnemyTypes) {
    for (int i = 0; i < currentDifficulty - enemyType.getDifficulty(); i++) {
        if(Math.random() < enemyType.spawnChance() ){
            spawnEnemy(enemyType);
        }
    }
}

```
> 2 votes

---
Tags: game-design, javascript, difficulty, dynamic-difficulty
---


title: How can AI compute movement in 2D games

text:
# Question
Title: How can AI compute movement in 2D games
I know how to create a basic AI for a game, where the AI simple creates units that only march forward. The AI only decides when to create a new unit, taking into account a number of considerations.

But now, I'm working on a game where the user controls a spaceship that can move in any of 8 directions (up, down, left, right, and any of the 4 diagonals).

The user is battling another spaceship that moves in the same way. The spaceships can shoot missiles. The missiles fly in the direction the shooting-spaceship is facing.

I need to program the AI, but have no idea how to make such an AI. Could you give me some general direction on how to make an AI that computes it's movements on the screen?

I have some very general idea, I would also like to know if this is somehow a decent direction:

The AI ship always tries to get inside a specific radius from the user's ship. Once it does, it moves up, down, left, or right to a point where it will be able to hit it's opponent. Then it shoots a missile in the direction of the user's ship.

Is this a decent direction? Any ideas or places where I can get started learning these things? My main concern is how the AI will compute it's movements.\

**EDIT**: Both the enemy ship and the player's ship can face any direction.

Thanks

# Answer
> 1 votes
Take the players ships position, and subtract it with the enemy ships postion. The resulting vector is the vector the enemy has to travel to reach the player ship. You can use this vector to travel the enemy ship within the specified radius of the player ship.

Like so:

```
vec4 playerPos = player.position;
vec4 enemyPos  = enemy.position;
vec4 toPlayer  = playerPos - enemyPos;

float distance = (((toPlayer)^2)^(1/2)); //don't kill me if I got this wrong

if (distance <= radius) {
   enemy.travel(toPlayer*(delta/1000));
}

```

Which direction does the enemy ship face? Can it turn to face the player ship? We need to know this.

Edit:

I see now that there indeed seems to be arbitrary facings. In that case, rotate the enemy ship to the same vector it uses to move to the player. If it shoots a missile at this point, it will hit the player, if the player does not move.

---
Tags: ai, movement, shooter
---


# Question
Title: How do I keep different platforms code in separate plugins?
Considering that some game platforms are under NDA and that publishing code publicly using their SDK is not allowed, how do game engine usually manage keeping plugins for different platforms separated?

For example if I make a plugin for PS3 export, it needs to be distributed only to people that do have the PS3 license.

Platform code can happen in many places of the code, and keeping it entirely separated from the core engine seems really hard/impossible to manage to me.

Edit for example:

If I make an open source game engine for which users are allowed to see the code, it means that the core engine is entirely viewable. Using preprocessors or anything like that would allow people to view code subjected to NDA, which doesn't work.

So, the platform-specific code needs to be totally separate from the core engine, but the core engine needs to be able to use it. The most obvious solution is to duplicate implementations of system things for every platform, and when using a plugin you select which implementation you use, but it seems very hard to maintain.

# Answer
> 1 votes
Here's how I did in my current project. I am developing a 2D User Interface library as part of my 3D engine. I am targeting several Windows environments: Windows 7/8 Desktop, Windows Store, Windows Phone OS. Although they are all based on Microsoft technologies, they are sufficiently distinct that they require different implementations. Such as the differences between net4x APIs and the RT PCL subset

In the case of my UI library, I have a main assembly that handles the internal logic of the UI controls (and it is a PCL library). For example it defines what happens when a control is intersected by a point (an intermediate, platform-agnostic point structure, not related to any real-world platform implementation), how to layout them and so on. It provides base classes for all controls supported by the library. There is a LabelBase, ButtonBase, PanelBase, and so on.

Then I have different subassemblies: one for net4x/RT and one for Windows Phone. The first is able to use Direct2D for the actual rendering. As D2D is not yet available on WP8 (at least through SharpDX), the WP8 assembly builds control shapes manually by computing the needed vertices (or using "baked" pre-rendered controls). All controls in the platform specific assembly inherit from the abstract control in the main one. Basically they just add the functionality needed to render themselves through two base methods (i.e.: Initialize and Render or something of that sort).

I use a similar logic for initializing the application. The .Windows assembly uses a form, .Windows8 uses XAML, WP8 uses something specific for that platform and so on. Networking is also supported through platform specific assemblies.

I think that using preprocessor directives on a large scale soon gets messy and I don't really like that. I only use it when it is unavoidable. For example right now you cannot have a PCL assembly that supports Desktop/Store/WP8. So the main assembly still needs to be recompiled, but that can be handled relatively easily through VS.

---
Tags: architecture, cross-platform, console
---


# Question
Title: How should I implement basic spaceship physics?
I am new to 2D game development.

I've made several games, but they've made almost no use of physics. Now I want to try making a game that uses some basic physics to look more realistic.

The game involves spaceships battling in space. I'm ignoring gravity. Each spaceship can move up, down, left, right or any of the 4 diagonals.

I want each spaceship to *accelerate when moved* (up to some threshold speed) and *gradually slow to a stop otherwise*.

I'm planning to give each spaceship a `velocity` and `acceleration` attribute.

The `acceleration` is set to some *constant* value. For example, 5.

When the spaceship starts moving, the `velocity` is set to some initial value. Then every period of time as long as it should be moving (for example every 30 milliseconds), the `acceleration` value is added to it.

When the user stops moving the ship, the reverse process happens: the `acceleration` value is decreased from `velocity` until velocity equals 0.

I have two questions regarding this:

1. Is this general type of physics realistic and/or common in games? **Is this the right direction?** Am I forgetting some factor or anything to be considered?
2. Regarding the specific implementation I'm planning: Is the right way to accelerate is add a **constant** value to the speed of the object? Or do I need to gradually increase the value added to the speed, thus increasing the acceleration?

# Answer
> 5 votes
Any physics "simulation" is going to deal with forces. Your approach may be basic, but it is definitely a step in the right direction to understanding game physics.

Now you may be able to add to this further. For example, if the player is turning around while moving at a high speed, how do you handle this? Do you prefer they continue along their original direction a bit until they correct to the new one, or should they just snap to the new direction at the same speed?

To answer your second question, let's first understand what acceleration means. For example, is your spaceship like a car where your acceleration is lower the higher your speed is, eventually capping at a certain maximum? Maybe this kind of change would break your gameplay, so these choices are entirely up to how you'd prefer your game to feel.

# Answer
> 3 votes
In real space, there is no friction. When you accelerate a body, it keeps moving in that direction and never stops, unless you accelerate it in the other direction. There are also no top-speeds. Given enough energy, you can accelerate a body to unlimited speeds.

There are games where such realistic physics are part of the gameplay, but the vast majority of games, especially those which focus on action instead of realism, handle this differently and add friction to space.

A simple and frequently used (but not physically correct) way to deal with friction is to have an acceleration value, a top-speed value and a deceleration value.

While the player presses the left/right key, each game-loop the acceleration-value is added to the current speed of its character. That means unless the character has already reached the top-speed.

When the player stops pressing the directional key, the deceleration value is applied in the opposite direction to slow the character down.

Often the acceleration is higher than the deceleration, so the player can break faster by pressing into the opposite direction than just stopping to press any button.

# Answer
> 1 votes
With the engines' propulsion as the only force acting on the spaceship, physics are hardly at play here. Your currently planned implementation are in accordance with 'realistic physics'. You could definitely design a spaceship that flies that way. To answer your second question, that too would be realistic. You could definitely design a spaceship that uses a non-constant force to reach its target velocity.

If you spaceship design is very specific, i.e. you know its mass, where the engines are, how much thrust they can produce and how much fuel they burn, how the controls work..., then you can run a physics simulation to determine exactly how that design is supposed to behave. Without these specifications, who is to say your ship handles incorrectly?

Your constant force-approach is simple to implement. Build it and play the game to see whether it needs tweaking.

---
Tags: 2d, physics
---


# Question
Title: Texturing a PyOpenGL 3D Cube with PySDL2
So, I've just started learning OpenGL with PySDL2, and I've created a class that will create a cube to the window that I've created with PySDL2. What I'd like to do now, is to figure out a way to texture the cube. I don't believe that the actual texturing part is the problem, but actually loading the image. I've tried to do this with PySDL's image loader, but this causes an error from the OpenGL texture creator. Here is my code to load an texture and bind it to OpenGL:

```
def LoadTexture(self, filename):
    """Loads a texture for the cube"""
    surface = SDL_LoadBMP(filename)
    #Checks if the loading succeeded
    if surface:
        #Translate the LP_SDL_Surface-pointer got from SDL_LoadBMP() to a real SDL_Surface
        texture_surface = surface.contents
        texture_format = GL.GL_RGBA
        GL_TEXTURE_ID = GL.glGenTextures(1)
        GL.glBindTexture(GL.GL_TEXTURE_2D, GL_TEXTURE_ID)
        GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
        GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, texture_surface.w, texture_surface.h, 0, texture_format, GL.GL_UNSIGNED_BYTE, texture_surface)
        return GL_TEXTURE_ID
    return None

```

And the error that gives looks like this:

```
TypeError: ("No array-type handler for type <class 'sdl2.surface.SDL_Surface'> (value: <sdl2.surface.SDL_Surface object at 0x030762B0>) registered", <OpenGL.GL.images.ImageInputConverter object at 0x02EC49F0>)

```

I'm using Python 3 so using something like PIL won't work for me. Any ideas how to get the texture loaded, preferably with PySDL2?

# Answer
> 2 votes
You should use the 'pixels' member of SDL\_surface to get the raw image data. See SDL\_Surface.

---
Tags: opengl, sdl, python
---


# Question
Title: Why does my HTML5 game loop (with masking) run slowly?
I have a game loop like so:

```
setInterval(function()
{
    context.save();
    context.rect(26, 144, 745, 400);
    context.clip();
    context.drawImage(myImage, 100, 100, 900, 900);
    context.restore();
}, 40);

```

As it runs the canvas gradually slows down to a stop. If I put the drawImage outside of the clipping then it runs indefinitely at the correct speed. Is there something I'm doing wrong?

# Answer
Using `setInterval` with such a low interval period means that the drawing is probably being queued up before the previous function has finished calling (for example, the drawing takes 50ms and your interval is 40ms, then it will always be trying to catch up).

I would recommend using `requestAnimationFrame`, a polyfill example can be found here. Here's a simple example:

```
window.requestAnimationFrame(function(){
    context.save();
    context.rect(26, 144, 745, 400);
    context.clip();
    context.drawImage(myImage, 100, 100, 900, 900);
    context.restore();
});

```

If you cannot, for some reason, use that you should do a timeout rather than an interval, and only restart the timer after your scene drawing have been completed.
> 6 votes

---
Tags: javascript, html5
---


# Question
Title: How can I use a Unity C# script simultaneously in a non-Unity Linux program?
I have a C# script inside a Unity project. I'd to both keep using the script in this Unity project, *and* to use it to compile a non-Unity Linux daemon.

So I would basically need to create a new `Main` for this Linux daemon, and include this script, without using any of Unity's classes. Compiling it using Unity anyway is currently not an option.

However I'm a bit confused on how to do such a thing. How am I supposed to do that?

# Answer
> 1 votes
You can compile a .DLL from any mono project, and use that in Unity.

Move the portions of the code you want to keep outside the unity project to a new solution, and compile a DLL from them.

You can then import that DLL and use it in your Unity project.

Unity themselves provide examples of how to do this here :

http://docs.unity3d.com/Documentation/Manual/UsingDLL.html

The "daemon" you want to run can be created in a side project, and compiled separately.

---
Tags: c#, unity, linux, macos
---


# Question
Title: Creating a gradient for a texture - Why is the color becoming dark on one side?
**Updated**
While debugging I looked at the lerp and it was calculating into a negative number at the start. So I added in checks for to low or high a value, and that seems to have fixed it. I'll answer the question myself unless someone can find a way to fix the formula that calculates the lerp, since that seems to be the culprit. My fix was this:

```
double lerp = (start - here) / (start - end);

if (lerp < 0d)
    lerp = 0d;
if (lerp > 1d)
    lerp = 1d;

```

**Original Question**
I'm applying a gradient to a texture per the answer in this topic: Code to generate a color gradient within a texture using a diagonal line

My code is referenced below. The code was seeming to work fine. I was using a two-color gradient: green to purple. **However**, when I changed it to two colors that blended well into a 3rd color, I could instantly see that something was wrong.

For example, blue to purple was producing a red element outside of the gradient area. If you also look closely, the blue itself is also enhanced on the outer edges. It's almost as if the two colors are mixing outside of the gradient area, when they should be the original colors.

**Calling Code**

This is applying to the center of an area 80x25.

```
Color[] colors = new Color[] { Color.Blue, Color.Purple };
float[] colorStops = new float[] { 0f, 1f };

Algorithms.GradientFill(new Point(40, 12), 3, 33, new Rectangle(0, 0, CellData.Width, CellData.Height), colors, colorStops);

```

**Gradient Calculation Code**

```
public static void GradientFill(Point position, int strength, int angle, Rectangle area, Color[] colors, float[] colorStops)
{
    double radians = angle * Math.PI / 180; // = Math.Atan2(x1 - x2, y1 - y2);

    Vector2 angleVector = new Vector2((float)(Math.Sin(radians) * strength), (float)(Math.Cos(radians) * strength)) / 2;
    Vector2 location = new Vector2(position.X, position.Y);

    Vector2 endingPoint = location + angleVector;
    Vector2 startingPoint = location - angleVector;

    double x1 = (startingPoint.X / (double)area.Width) * 2.0f - 1.0f;
    double y1 = (startingPoint.Y / (double)area.Height) * 2.0f - 1.0f;
    double x2 = (endingPoint.X / (double)area.Width) * 2.0f - 1.0f;
    double y2 = (endingPoint.Y / (double)area.Height) * 2.0f - 1.0f;

    double start = x1 * angleVector.X + y1 * angleVector.Y;
    double end = x2 * angleVector.X + y2 * angleVector.Y;

    for (int x = area.X; x < area.Width; x++)
    {
        for (int y = area.Y; y < area.Height; y++)
        {
            // but we need vectors from (-1, -1) to (1, 1)
            // instead of pixels from (0, 0) to (width, height)
            double u = (x / (double)area.Width) * 2.0f - 1.0f;
            double v = (y / (double)area.Height) * 2.0f - 1.0f;

            double here = u * angleVector.X + v * angleVector.Y;

            double lerp = (start - here) / (start - end);

            float newLerp;
            int counter;
            for (counter = 0; counter < colorStops.Length && colorStops[counter] < (float)lerp; counter++) ;

            counter--;
            counter = Math.Max(counter, 0);
            counter = Math.Min(counter, colorStops.Length - 2);

            newLerp = (colorStops[counter] - (float)lerp) / (colorStops[counter] - colorStops[counter + 1]);

            SetPixel(x, y, color);
        }
    }
}

```

# Answer
> 0 votes
The answer is that the amount to use during the lerp method was going below 0 or above 1. This will fix it:

```
lerp = MathHelper.Clamp((float)lerp, 0f, 1.0f);

```

---
Tags: xna, c#, graphics, color
---


title: XNA blurring moving images

text:
# Question
Title: XNA blurring moving images
Why does XNA blurs the images which moves less than 1px in between two draws? It is quite annoying, because everything looks really blurry. Is there a way to disable it?
I have tried to set the SamplerState of the spritebatch's SamplerState to PointWrap in it's Begin function, but then it wraps the images to pixels, thus they move choppy. Any suggestions? Thanks!
My SpriteBatch's Begin function:

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

```

**Edit**:

```
public class Image:IDisplay
{
    public Texture2D texture;
    private BaseModel model;
    private Vector2 position;
    private Util.DISPLAY_LAYERS layer;
    public Image(String asset, BaseModel _model)
    {
        model = _model;
        texture = Main.current.Content.Load<Texture2D>(asset);
        DisplayManager.add(this, model.layer);
    }
}

```

This is how the Image class looks like (without additional functions), and this is it's draw function which is being called.

```
public void Draw(SpriteBatch batch)
    {
        if (model== null)
        {
            batch.Draw(texture, position, Color.White);
        }
        else {
            position.X = (int)Math.Round(model.Position.X, MidpointRounding.AwayFromZero);
            position.Y = (int)Math.Round(model.Position.Y, MidpointRounding.AwayFromZero);
            batch.Draw(texture, position, Color.White);
        }
    }

```

# Answer
The problem is the renderer is anti-aliasing that sub-1px difference. You can disable this by either setting the sampler state to point clamp in your `SpriteBatch.Begin` call like so:

```
sb.Begin(
    SpriteSortMode.Deferred,
    BlendState.AlphaBlend,
    SamplerState.PointClamp, // <------
    DepthStencilState.None,
    RasterizerState.CullCounterClockwise,
    null,
    Matrix.Indentity);

```

However anti-aliasing is beneficial for rotated and non-integer scaled objects. My suggestion would be to not have floating point drawing positions.

So that you don't have to refactor your positions to `int`, I would suggest you either cast your coordinates to `int` in the drawing method, or for better accuracy (for a marginal performance hit), round them and then cast to `int` like so:

```
    spirteBatch.Draw(
        _texture,
        new Vector2(
            (int)Math.Round(posX, MidpointRounding.AwayFromZero),  // <------
            (int)Math.Round(posY, MidpointRounding.AwayFromZero)), // <------
        null,
        _drawColor,
        _rotation,
        new Vector2(_texture.Width / 2, _texture.Height / 2),
        _scale,
        SpriteEffects.None,
        0
    );

```

It's probably better to get in to the habit of having `_drawX`/`_drawY` as fields defined outside of a method so that you can calculate the draw coordinates within an `Update()` method. This is better because if you were ever trying to find a bottleneck or bad code, having all your logic being done from one method makes it easier to track it down.
> 1 votes

# Answer
You can truncate/round the float coords of the position of the sprites into int (only do this during the Draw() method). This will avoid the blurred effect, since the graphics card will not need to deal with "broken" coords.
> 0 votes

---
Tags: xna, c#, 2d, xna-4.0, graphics
---


# Question
Title: Pygame collision detection less frequent when objects are increased
I currently experiencing an issue in pygame where whenever i increase the number of objects e.g. platforms, rocks

```
for a in range(150):
    rock = Rock(0,0)

```

**OR** incresing the range which they spawn in:

```
rock.rect.x = random.randrange(-200,30000)
rock.rect.y = random.randrange(80,500)
rock_list.add(rock)
all_sprites_list.add(rock)

```

**LINE 232**

(which i really need to do for an **ENDLESS** mode) **collision detection between the player and all the objects that have have been changed will become less frequent, so the character will just go through th objects as they weren't even there... you can see the character fall through the objects, it falls through in front of the object and not behind**. All game code is below, I have tried a number of different techniques and values but I have found that these numbers and ranges work best.

Collision Detection code: **FOR PLATFORM**

```
medium_collide = pygame.sprite.spritecollide(player, medium_list, False)
if medium_collide:
    player.rect.y-=2

```

**FOR ROCK**

```
    rock_collide = pygame.sprite.spritecollide(player, rock_list, True)
    if rock_collide:
        lives-=1
    if rock_collide:
        player.rect.y = 100
        player.rect.x = 50

```

***!!!!!GAME CODE BELOW!!!!!***

**GAME CODE**

# Answer
Can't say much without seeing your whole code, but I guess you're just testing collision for all objects in the game. Instead, do a AABB (rectangular) collision test to see if objects are near enough to matter (usually if they are on-screen). If they are, then do your more complex collision detection. Note that this will actually degrade performance extremely if you have all objects of the game on-screen at the same time, and you'll need to adjust this pre-check to fit your game.
> 3 votes

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


# Question
Title: Can sprite sheet width and height affect performance?
Is there any performance difference in the way the images are placed inside a sprite sheet image (for the same total area)?

For example, should I place 50 sprites (50x50 each) in a linear way creating a sheet of dimensions 50x2500px? Or is it better to split into multiple rows, say 10 sprites per row, and get a sheet of dimensions 500x250?

Assume that the graphics are hardware accelerated.

# Answer
It is possible that the *total size* of a sprite sheet will affect performance of your game in some reasonably small fashion. *Extremely small* sprite sheets generally mean that you have many, which in turn implies many state changes, and frequent state changes are not good for performance. *Extremely large* sprite sheets consume more GPU RAM, and if they need to be purged and recreated, or reshuffled due to resource virtualization of the GPU, this can cause a delay.

Keeping the same total pixel area and varying the dimensions of the sheet should not cause a noticeable variance in performance however.

As with most things performance-related, to determine whether or not a subject is actually an issue in your game you should *profile* it.
> 7 votes

# Answer
Put the profiler on it. Try a huge sheet and a small one. Measure the difference.

This is the very best way to answer these questions, since you don't want opinions: you want answers. Doing this test yourself is the best way to get an answer, since it will be for your actual use case.
> 2 votes

# Answer
Profiling is a good idea. You should remember you don't need real sprites. You could profile with noise instead. I personally think the shape of a sprite sheet is mostly a result of how we view it on a screen and the goal is too keep it easy to view so an extreme width is bad for that purpose.

I will also add that it is very unlikely the choice here will have a very noticeable effect on performance. It is always better to profile first before you decide what to optimize. Always optimize the part of the code that takes the longest amount of time to run until you are sure it is nearly fully optimized.
> 1 votes

# Answer
To optimize the rendering process of your graphic engine you should create sprite sheet with 2^n width and 2^m height (2x2 ... 128x256 ... 512x256 ... 1024x1024...)

Be aware, some engine like Corona SDK doesn't support more than 2048x2048 sprite sheet. Check the specification of your graphical engine. You can also use software like Texture Packer in order to optimize the arrangement of your sprite sheet.
> 1 votes

---
Tags: html5, performance, spritesheet, gpu, hardware-acceleration
---


# Question
Title: Directional shadow mapping view/projection matrices
I've got shadow mapping with directional lights working, but I believe I am constructing the view/projection matrices wrong.

Here's how I build them:

```
Mat4 viewMatrix = LookAt(lighting.mCameraPosition + (directionalLight.mLightDirection * Z_FAR / 2.0f), -directionalLight.mLightDirection, Vec3(0.0f, 1.0f, 0.0f));
Mat4 lightVP = CreateOrthographicMatrix(-Z_FAR, Z_FAR, -Z_FAR, Z_FAR, Z_NEAR, Z_FAR) * viewMatrix;

```

The problem is the shadows become skewed and change depending on the camera position, which is bad. What is the proper way of doing this?

EDIT:

1) No, that is what I'm not sure about; currently as you said it is the camera position and thus the shadows moves around when I move the camera, which is bad - what should be the actual position, since directional lights have no position?

2) Also using Z\_FAR DOES make it pixelated which is my second problem - but must not the boundaries be Z\_FAR in all directions, otherwise objects in the view range may not cast shadows?

# Answer
You have two problems here:

First problem:

Adding some kind of position offset to your lookat matrix (currently your camera position) is essentially supposed to center the "light camera" (whatever your light source sees from its view) around that position. This is done because the shadow map will only cover a limited range, but if your shadow maps in one directions extends to 10 \[whatever distance unit you have\], but objects are positioned at 12\[whatever distance unit you have\], you obviously still want those objects to cast shadows. So you apply this position offset to all objects via the shadow caster view transform, so they're essentially "pushed into" the visible range of whatever the camera sees.

The reason this causes artifacts if done in a straight forward way is because due to how rasterization works, the amount of pixels that are rasterized for each object are not the same if you change positions of either the objects or of the visible range that the camera sees. The solution to this is to snap that position offset you apply to multiples of the shadow map texel size. I.e. the offset you apply must be a multiple of the shadow map texel size in each direction. You do this by just taking your normal offset, and snapping it to a multiple (either the nearest, or just floor/ceil, doesn't matter I think) of the texel size.

```
vec3 camPos = lighting.mCameraPosition;
vec2 texelSize = 1.0f/shadowmapResolution;
vec3 snappedCamPos = floor(camPos / texelSize) * texelSize; //this is what you apply instead of lighting.mCameraPosition, in this case I rounded down.

```

Second problem:

An orthographic projection matrix covers a certain width and height, and since you want all objects that might somehow influence whatever the user camera sees to cast shadows, the naive solution (what you're doing right now) is to make the projection matrix cover such a large range that all objects will definitely be inside it. The problem, however, is that this projection matrix essentially maps the x/y positions of your objects into the \[-1,1\] range, and the rasterizer will then use this information to actually fill pixels in the texture you're drawing to. For example, if the rendertarget resolution is 2x2 pixels, then all positions falling in \[-1,0\] in both x and y coordinates will be rasterized to the same corner of that 2x2 shadow map. This of course results an extremely coarse shadow map where barely any detail is visible. In this case, the culprit is the low shadow map resolution, but while your case suffers from the same low-detail problems, the cause is something different. Since your orthographic projection matrix covers such a large range, a huge range of "world space distance" is mapped down to the \[-1,1\] range and triangles being huge distances apart in world space might be rasterized to the same pixel.

The solution to this is to make sure that your orthographic projection matrix only covers just a large enough range so it sees all objects that might influence the view frustum of the user camera. For now, you can try to manually adjust the range, by taking out z\_far and setting manual values (this depends on how large your objects are, etc.), e.g. start with a shadow map from -10 to 10 in all directions and increase or lower the range until the results look right. But that's only a hack to get it working in the beginning, if you want to do it properly you should adjust the range dynamically. Check this article under "Calculating a Tight Projection"
> 3 votes

---
Tags: opengl, shadows, shadow-mapping
---


# Question
Title: Should I create .fla files in Flash Professional and import them into Flash Builder?
With Flash Builder and Flash Professional at my disposal for creating games, I'm having a hard time figuring out if I should be creating the `.fla` files in Flash Professional and then importing them into Flash Builder, or something else? Does it matter?

# Answer
You can use Flash Professional to create graphics and do your animating, building the content as .swfs, and then import those into Flash Builder where you do all the programming. Flash Builder doesn't do anything with .fla files directly.
> 1 votes

---
Tags: flash
---


# Question
Title: How long will it take to jump from point A to point B?
I need to know how long it takes to jump from one point to another. Because if the jump time takes for example 2.0f(float jumptime = 2.0f), a jump animation is played during a time interval of exactly 2.0f. The difficult thing is, I need to know the jump time before the jump was executed.

Is it possible to calculate that right before the jump is executed or is it impossible to calculate that?

I use the following formula to let an object(ball) jump from one platform to another platform:

impulse = Vector2(distance.x / time * mass + gravity.x / 2 * time * mass, distance.y / time * mass + gravity.y / 2 * time * mass);

Description of the jump

**Update:**

My calculations:

```
float gravity = 3, timetopeak, timetoground, totaljumptime, waytothetop, waytotheground;

timetopeak = jumpForce.Y / -gravity;
waytothetop = (float)(0*timetopeak + 0.5*-gravity*timetopeak*timetopeak);
waytotheground = Ball.Position.Y + waytothetop - (PlatformB.Position.Y - PlatformBHeight / 2.0f - BallHeight / 2.0f);
timetoground = (float)(Math.Sqrt(2 * waytotheground / -gravity));
totaljumptime = timetopeak + timetoground;
Ball.ApplyLinearImpulse(ref jumpForce);
//I divide the totaljumptime because the animation has 5 frames.
BallAnimation = new Animation(totaljumptime/5, 32, 32, Animation.Sequences.forwards, 0, 5, false, true);

```

Are my calculations correct? Because the totaljumptime is very small and my animation runs much too fast.

# Answer
Sure you can know the time, as long as you know the initial velocity, the acceleration (gravity), and the difference in height between point A and point B (this is crucial: if you don't know where the ball is landing, naturally you won't know the duration of the jump).

If the ball has an upward velocity of **v**, and it accelerates downward at a rate **a**, then the time taken for it to reach the peak of the jump is simply **t = v/a**. To know how far up it travelled, this equation comes in handy:

```
s = ut + 0.5at^2

// s = distance
// u = initial velocity
// a = acceleration
// t = time

```

Plug in our values (**v** for **u**, and make sure **a** is negative), and then we move on to the next step. You know how long it took to get to the peak of the jump. How about down? Well, if it's landing at the same height it started, then the duration is the same. **t * 2**. Otherwise, you need to find the distance it still has to travel:

```
initial height + height travelled upwards - final height

```

(s = ut + 0.5at^2 is what we used to get the distance travelled upwards)

Once we have that, use the same formula again, this time rearranging to solve for **t**:

```
s = ut + 0.5at^2
// since the initial velocity is 0, it becomes:
s = 0.5at^2
2s = at^2
root(2s/a) = ±t
t = ±root(2s/a) // Note, we want the positive answer

```

And there you go, you got the time for the ball to drop from the peak of its height. Add that to the time it took to get to the peak of the jump, and you've got the overall time.

If that wasn't well illustrated enough, look up *projectile motion*.

(Yes, the above could be simplified into a single equation, but, I find that it's more intuitive to understand as I've illustrated it above.)
> 0 votes

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


# Question
Title: Combine framebuffer-textures to default framebuffer
I know frame-buffers are not textures themselves, but they do contain a texture, given they are set up correctly, which I believe mine are, as:

```
(status == GL_FRAMEBUFFER_COMPLETE)

```

returns true.

The reason I am using multiple frame-buffers is so that I can perform some post-processing on individual objects/layers - *is this even a best-practice approach?*. So I render to a bunch of textures, and to not end up with a black screen, due to never rendering to the default frame-buffer, I need to somehow combine the frame-buffers/textures into the default frame-buffer.

My naive approach would be to bind the default frame-buffer and then just make a simple shader-program that would write each texture back to the screen.

This seems like a task that could be optimized through some built-in function specially for this as it must be a standard thing now'a'days, so what is the correct way to combine a bunch of frame-buffers/textures into one (the default frame-buffer)?

# Answer
Sorry to break it to you, but if you're using a shader based pipeline (as opposed to fixed functionality), then your "naive" approach is the standard approach.

Deferred rendering, which most modern graphics engines have adopted, involves rendering various aspects of the scene to different textures. Typically things such as the normals, depth, diffuse and specular albedo. They are then sampled at the next stage, to calculate per-pixel lighting. It might be drawn multiple times to framebuffers, and to multiple textures, to implement things like SSAO, bloom, field of depth, and so on. Even if it's something simple like an additive blend, it's usually done with a shader.

So go ahead and use as many textures and FBOs as you need, *but only as many as you need.* Moving around lots of texture data *will* have an impact on performance, so whenever possible, try to combine post-processing steps to reduce the number of passes you need to make.
> 1 votes

---
Tags: opengl, glsl, frame-buffer
---


# Question
Title: Simple curiosity about glDrawElements function
I've written a very simple OpenGL program displaying a white cube. To do the job done I recovered vertex position and indice data from an OBJ file that describes my cube. Here's the OBJ file content :

```
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
usemtl BoxMtl
s off
f 1 2 3
f 5 8 7
f 1 5 6
f 2 6 3
f 3 7 4
f 5 1 4
f 4 1 3
f 6 5 7
f 2 1 6
f 6 7 3
f 7 8 4
f 8 5 4

```

According to the OBJ file the vertex array is translated in C by :

```
static GLfloat position[24] =
{
    1.000000, -1.000000, -1.000000,
    1.000000, -1.000000, 1.000000,
    -1.000000, -1.000000, 1.000000,
    -1.000000, -1.000000, -1.000000,
    1.000000, 1.000000, -0.999999,
    0.999999, 1.000000, 1.000001,
    -1.000000, 1.000000, 1.000000,
    -1.000000, 1.000000, -1.000000
};

```

And the index array by :

```
static GLuint indices[36] = {
    0, 1, 2,
    4, 7, 6,
    0, 4, 5,
    1, 5, 2,
    2, 6, 3,
    4, 0, 3,
    3, 0, 2,
    5, 4, 6,
    1, 0, 5,
    5, 6, 2,
    6, 7, 3,
    7, 4, 3
};

```

Now the code to initialize the VBO for the vertex array :

```
GLuint vertex_vboId;
glGenBuffers(1, &vertex_vboId);
glBindBuffer(GL_ARRAY_BUFFER, vertex_vboId);
glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(GLfloat), position, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

```

The one for the IBO :

```
GLuint indexId;
glGenBuffers(1, &indexId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexId);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 36 * sizeof(GLuint), indices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

And finally the code to render the scene in the main loop (here the white cube):

```
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertex_vboId);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, OFFSET_BUFFER(0));
glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexId);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, OFFSET_BUFFER(0));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

Here's the output :

Until here there's no problem ! But my objective is to render the same cube but this time with a texture (a uv map) and with a UNIQUE call of glDrawElements like above.

To do the job done, I've first created a uv mapped cube on Blender and exported a new OBJ file but, this time, with vertex texture (vt) like below :

```
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
vt 0.626059 0.265705
vt 0.626059 0.487398
vt 0.404365 0.487398
vt 0.626060 0.930786
vt 0.404365 0.930786
vt 0.404365 0.709091
vt 0.847752 0.487397
vt 0.847753 0.709091
vt 0.626059 0.709091
vt 0.182672 0.487397
vt 0.626059 0.044011
vt 0.404366 0.265704
vt 0.182671 0.709091
vt 0.404366 0.044011
usemtl BoxMtl
s off
f 1/1 2/2 3/3
f 5/4 8/5 7/6
f 1/7 5/8 6/9
f 2/2 6/9 3/3
f 3/3 7/6 4/10
f 5/11 1/1 4/12
f 4/12 1/1 3/3
f 6/9 5/4 7/6
f 2/2 1/7 6/9
f 6/9 7/6 3/3
f 7/6 8/13 4/10
f 8/14 5/11 4/12

```

So I wonder if it's possible to use glDrawElements with two kinds of indices (v and vt) in a unique indice array (with a size of 72 this time). I tried several way without any success. Or maybe I have to use glDrawArrays... I'm really lost. Thanks very much in advance for your help.

# Answer
No. There is no direct translation of the OBJ format into any graphics API (even D3D or bleeding edge OpenGL). What you have to do is duplicate the data. Here is a generic procedure:

1. For every index pair that exists in the face section, such as `1/1`, `5/4`, ..., `5/11`, etc. assign it a new index which is a single integer. So we might do:

```
1/1 -> 0
2/2 -> 1
3/3 -> 2
5/4 -> 3
...

```

But for example, `1/1`, `5/11`, etc. appear more than once, so we always give them the same index.
2. Now we assemble the data by looking up the indices backwards in the above table, and then copy that data to a new array. For example, `1/1 -> 0`. So in the vertex array, we put the 1st vertex position data and the 1st uvcoord into index 0. Similarly, we put the 5th vertex position and the 4th uvcoord into the index 3 slot in the vertex array.
3. Now you have all the positions and uvcoords in a vertex array buffer. Into an element array buffer, we put the face data, but instead of the original pairs, we place the assigned index, which now points into an array with the right data. (we might need to break quads here) We have turned something like `f 2/2 1/7 6/9` into `f 1 6 12`, or something, which the graphics card can support. Then you can use glDrawElements as normal.

Note this procedure duplicates some data, potentially a lot, but that is what is required to submit to the graphics card. This process can easily be extended for vertex colors/weights/etc. by considering triples, or 4-tuples of indices, etc.

Also, *please* don't implement this procedure this way, there are way more efficient ways to do this. Also this might not produce very optimal meshes in terms of transform cache behaviour.
> 1 votes

---
Tags: opengl, shaders
---


# Question
Title: How do I get parabolic movement in Unity using Rigidbody2d?
EDIT: It was the Animator after all. Apply Root Motion basically nullifies any physics based work.

I "know" this answer but I can't figure out what can possibly be wrong. My code is in FixedUpdate(). My Rigidbody2D has a Gravity Scale of 4 and a Mass of 1. For whatever reason a Gravity Scale of 1 just isn't strong enough to keep it from floating away. In the pictures below the little cubes should be marking each frame.

Using the below code I get a jagged leap movement. The object shoots upwards and falls like a feather.

```
if(Game.inputManager.GetKey("Jump").KeyPressed())
{
    yForce = 1000f;
    this.rigidbody2D.AddForce(Vector2.up*yForce);
}

```

And using another suggestion I distribute the force over a second of time.

```
if(Game.inputManager.GetKey("Jump").KeyPressed())
    {
        addForceTimer = 1;
        yForce = 1000f;
    }
    addForceTimer -= Time.deltaTime;
    if(addForceTimer > 0)
    {
        this.rigidbody2D.AddForce(Vector2.up*yForce* Time.deltaTime*4);

    }

```

And I get a more desirable but still just as wrong movement where there is no hang at the top of the jump.

From what I thought I knew neither of these should be happening at all. The object shouldn't be falling at a constant speed like it is. Does anybody have any suggestions?

The character is animated if that can possibly have some sort of effect but I don't imagine it would.

# Answer
Make sure that if the GameObject is animated that you turn off "Apply Root Motion". It is a setting on the "Animator" component. It will mess with the Physics of the object. I do not know the particulars. But I turned it off and voila, everything works fine now.
> 1 votes

---
Tags: unity, physics
---


# Question
Title: Where should shaders and lights be in a component-based entity system?
Where should I put the shader and the light / shadow calculation? Should that be a component too?

And should the rendering system know how to handle them or should there be a separate light system?

I'm specifically talking about about a 2D system, but it should be the same in for 3D I think.

# Answer
A component-based entity system works best when an entity represents something in the logical game world and a component some single aspect of that entity, generally things that you'd want to compose.

An entity may have a component that describes visual properties or behavior of an object. A component that represents a sprite or model, for example. It is perhaps appropriate to have a component that represents the fact that some entity emits light in a certain fashion. But those should just act as proxies, game-logic packages of information that are ultimately fed into the renderer in a more optimal form.

Do not make the mistake of going overboard with your "entity system" and putting *everything* in there. Not everything should be a component; it is a horrible way to architect anything at scale, and trying to homogenize everything in that fashion can result in extremely confusingly-coupled and poorly-performing code.

To that end, the renderer should not know about or process component types. It should understand the representation of sprites or models, shaders or lights in the viewable space and the rendering of those sprites/models/lights in an efficient manner. It should not have any dependencies on the entity/component system *at all* (I mean this literally: you should be able to compile the rendering code without including the component code).

Rather, have the components (which are naturally a game logic domain) store pointers or references to the renderer (which is naturally a lower-level part of the technology stack) if needed to avoid duplication of data or inefficiency state transfer every frame. But do not directly couple the entity system and the renderer.
> 4 votes

# Answer
I am implementing the same functionalities. Here's how I have architectured my engine:

Entities are not just renderable objects. In my ECS cameras and lights are also entities.

* I have a `ContentLoadingSystem<TComponent>` where `TComponent` can be a `ModelComponent`, a `ShaderComponent` (i.e., the actual bytecode), etc.
* this is where it gets tricky, the `ContentLoadingSystem` once a shader is loaded, it sends a `ContentLoadedMessage<TComponent>` to systems that have subscribed for that particular type of message.
* My `CameraSystem`, `PointLightSystem` etc all are subscribed to these messages, so when it is their turn to examine the message queue, they get a reference to the shader and are thus able to set various shader properties
* For example the PointLightSystem might want to set the light's colour. The ShaderComponent that is loaded also contains metadata that helps these systems to know which value to actually fetch from the engine.

I think that shadows should be handled by an independent system. Not all entities might want to cast a shadow. So the ShadowSystem would be responsible of rendering a ShadowMap for example and then set it to those shaders that request it. With the approach I used, if the `ShadowSystem` subscribes to `ContentLoadedMessage<ShaderComponent>`, it will be notified when each shader is loaded. Thus when initialising a shader, if its metadata contains a reference to a ShadowMap texture it will set it to the appropriate texture register.
> 1 votes

---
Tags: shaders, lighting, entity-system, shadows
---