title: LibGdx efficient data saving/loading?

text:
# Question
Title: LibGdx efficient data saving/loading?
Currently, my LibGDX game consists of a 512 x 512 map of Tiles and entities such as players and monsters. I am wondering how to efficiently save and load the data of my levels. At the moment I am using JSON serialization for each class I want to save. I implement the Json.Serializable interface for all of these classes and write only the variables that are necessary.

So my map consists of 512 x 512 tiles, that's 260,000 tiles. Each tile on the map consists of a Tile object, which points to some final Tile object like a GRASS\_TILE or a STONE\_TILE. When I serialize each level tile, the final Tile that it points to is re-serialized over and over again, so if I have 100 Tiles all pointing to GRASS\_TILE, the data of GRASS\_TILE is written 100 times over. When I go to load/deserialize my objects, 100 GrassTile objects are created, but they are each their own object. They no longer point to the final tile object. I feel like this reading/writing files very slow.

If I were to abandon JSON serialization, to my knowledge my next best option would be saving the level data to a sql database. Unless there is a way to speed up serializing/deserializing 260,000 tiles I may have to do this. Is this a good idea? Could I really write that many tiles to the database efficiently?

To sum all this up, I am trying to save my levels using JSON serialization, but it is VERY slow. What other options do I have for saving the data of so many tiles.

I also must note that the JSON serialization is not slow on a PC, it is only VERY slow on a mobile device. Since file writing/reading is so slow on mobile devices, what can I do?

# Answer
So in general, JSON works really well for storing parameters and settings, but for storing big blocks of data like tile maps, you'll probably want to use your own format. JSON can be really repetitive, storing 256K copies of the string "GRASS\_TILE", and that could be part of what's causing the slowdown.

Using a SQL database probably isn't what you want to do either. Like JSON, it can be great for setting and parameters, if there are a ton of them like sim games, but in general, it's best non-game applications, when you need just one row of data out of many rows.

Instead of JSON or SQL, I think a good alternative would be to store just one character per tile in a separate text file. So, for example, you could decide that 1 = "GRASS\_TILE", 2 = "STONE\_TILE", etc. Then a small field with a rock in it could look like

```
1111111111
1111221111
1111221111
1111111111

```

512x512 would be bigger of course, but you get the idea. The big saving here is that you're not storing the whole string "GRASS\_TILE" for every grass tile, so reading it into memory from disk will take less time. Then when you're loading it, you can use something like this:

```
FileHandle file = Gdx.files.internal("level_01.map");
String tiles = file.readString();
for(int y = 0; y < 512; y++) {
    for(int x = 0; x < 512; x++) {
        char tileType = tiles.charAt((y * 512) + x);
        if(tileType == '1') {
            addTile(x, y, "GRASS_TILE");
        }
        // etc
    }
}

```

This is just one option, but the advantage of this one is that you can read and edit your tile map since it's plain text. Another option would be to separate the values by commas, and that would let you call `String.split(",")` which will give you an array of tile values. The most flexible option, however, is probably to store the file as binary data, and then call `file.readBytes()`. Each tile/byte can be any value between 0 and 255, so you can have a lot of tile types, but the disadvantage is that the map itself would be harder to create and edit without external tools, which you may have to write yourself.

And finally, you mentioned that your loader was creating many copies of the same objects. If you don't need separate copies, then you could initially load that data in an ObjectMap (different kind of map!), and then look it up when you need it. You could use something like `ObjectMap<String, TileData>`, and then look up with your data with `dataMap.get("GRASS_TILE")` as needed.

**EDIT:**

In response to your questions in comments, I was thinking of using the `ObjectMap` as a place to store your unchanging data. So say you have an entity type called "bad\_guy\_01". Your JSON can look like:

```
"entities": {
  "bad_guy_01": {
    "name": "Bad Name",
    "hitPoints": 100,
    "activeTexture": "images/bad_guy_01_a.png",
    "inactiveTexture": "images/bad_guy_01_b.png",
  },
  etc...
}

```

Then your JSON loader can load `"entities"` into a `ObjectMap<String, EntityData>`. Now all this gets loaded at the beginning of the game, and that's all unchanging data.

Then later, when your code decides you need another entity of type "bad\_guy\_01", you'll want to create a new entity with just the changeable data, like `currentHitPoints`, `position`, `isActive`, etc. I usually just store all the active entities in an `Array<GameEntity>`, or sometimes use the `Stage` if you're using Scene2d.

The idea is that you leave it to you logic code to match the two. So for example, assume `entity.type` is "bad\_guy\_01", then whatever code is rendering the sprites can do something like

```
if(entity.isActive) {
    draw(entities.get(entity.type).activeTexture, entity.position);
} else {
    draw(entities.get(entity.type).inactiveTexture, entity.position);
}

```

Likewise, whatever is checking if the entity is alive can check the entity's `currentHitPoints` vs the entity data's `hitPoints`. You get the idea.

You can do the same thing for the maps. So you'll need a `Tile[] currentTileMap[512][512]`, where each `Tile` is something like

```
class Tile {
    String type;
    Entity currentEntity;
}

```

and the `type` is the lookup for the unchanging tile data, like the 1 = GRASS\_TILE, etc.

For serializing and writing out the map, if you need to write out the basic map with the tile type IDs, the 1s and 2s, then that you may need to do manually or create a map editor. If you need to write out the current state of the map, like for a save file, then you can write out the `Tile[512][512] currentTileMap`. If you can do that through the JSON serializer, then that size should be reasonable, esp if the output can be minified.
> 6 votes

---
Tags: java, android, libgdx
---


# Question
Title: Packet Loss Affecting Client-Side Prediction
I have been reading about client-side prediction lately and I have been thinking of ways to implement it into my multiplayer game. I think I have a pretty good understanding of client-side prediction but I am a bit confused of how packet loss will affect it.

For example, say the client moves left. The client moves left on its side and also sends a packet to the server. If the server received this packet, it would see it was a valid move and send a packet back validating the clients decision. But if the packet didn't make it, the server would not move left and if the client moves left again their move will seem invalid to the server, giving the client a choppy experience.

So my question is how is client-side prediction implemented without this problem? Thanks for your help.

# Answer
> 2 votes
Important commands need to be reliable. If you have some input, you need to do get it to the server. If the packet is dropped and not ACKed, you must resent it.

This is one reason that less twitchy games often just use TCP (with NAGLE off). Games that need UDP often end up having to reimplement much of TCP for *some* types of messages.

For instance, you can ACK every packet received all the time. If a packet is not ACKed with some time period, you resend only the messages in that packet that were marked as reliable. If you have time-sensitive messages, you may need something more complex were you resend the message only if a newer message of the same ID/type hasn't replaced it in the outgoing queue already.

Requisite reading: http://gafferongames.com/networking-for-game-programmers/

You might also look into RakNet, ENet, or several other libraries that already implement all these bits.

---
Tags: networking, client-server, movement-prediction
---


title: Fade in screen in pyGame?

text:
# Question
Title: Fade in screen in pyGame?
So I wanted to make my menu fade in when the game starts and fade out when it quits. To do so, I created a second surface and planned to fill it with black and then gradually increase alpha. So in the constructor I added:

```
    self.fadeInSurface = pygame.display.set_mode(screen_size, flag)

```

In the main game method before the game loop starts:

```
self.fadeIn()

```

And the aforementioned `fadeIn()` looks like this:

```
def fadeIn(self):
    for i in range(100):
        self.fadeInSurface.fill((0,0,0))
        self.fadeInSurface.set_alpha(i)
        self.clock.tick(30)
        pygame.display.flip()

```

But instead of a fade-in, all I get is solid black screen for a short time and then the menu appears without any eye candy whatsoever. What am I doing wrong?

EDIT: Thanks to @Heckel, I made something like this:

```
def fadeIn(self):
        for i in range(255):
            self.surface.blit(self.background, (0,0), None, BLEND_RGB_MAX)
            self.surface.blit(self.curStart, (100,200), None)
            self.surface.blit(self.curQuit, (400,350), None)
            self.fadeInSurface.fill((0,0,0))
            self.fadeInSurface.set_alpha(255-i)
            self.surface.blit(self.fadeInSurface, (0,0))
            self.clock.tick(30)
            pygame.display.flip()

```

so that I have the main surface (called surface) on which I project my buttons and background and a secondary surface (called fadeInSurface) which is solid black but its alpha changes. Running this code, however, still results in solid black screen for a few seconds and then a sudden change to full clarity of the whole menu :( Why is that so?

# Answer
> 2 votes
Very good idea, I must say. I've solved the problem. First of all, you absolutely don't need to use a for-loop (That's the reason why things happen pretty fast).

I ask you:

The game does not have a main loop already? In your code, in the very first frame of the game, you run a loop that increment all the colour-value up to its maximum. So, that's the problem.

I'm not using your variables, but hopefully my example will be understandable. Try something like that:

```
from pygame import *
DONE = False
screen = display.set_mode((1024,768))
alphaSurface = Surface((1024,768)) # The custom-surface of the size of the screen.
alphaSurface.fill((255,255,255)) # Fill it with whole white before the main-loop.
alphaSurface.set_alpha(0) # Set alpha to 0 before the main-loop.
alph = 0 # The increment-variable.
while not DONE:
    screen.fill((0,0,0)) # At each main-loop fill the whole screen with black.
    alph += 0.1 # Increment alpha by a really small value (To make it slower, try 0.01)
    alphaSurface.set_alpha(alph) # Set the incremented alpha-value to the custom surface.
    screen.blit(alphaSurface,(0,0)) # Blit it to the screen-surface (Make them separate)

    # Trivial pygame stuff.
    if key.get_pressed()[K_ESCAPE]:
        DONE = True
    for ev in event.get():
        if ev.type == QUIT:
            DONE = True
    display.flip() # Flip the whole screen at each frame.
quit()

```

You should be able to run this code properly. I hope it helped.

The opposite:

```
alphaSurface.set_alpha(255) # Set alpha to 255 before the main-loop.
alph = 255 # The Decrement-variable.
alph -= 0.1 # Decrement alpha by a really small value (To make it slower, try 0.01)

```

# Answer
> 1 votes
You need a `blit` before the `flip` to display your black surface. The solid black comes from the fact that you don't display anything on the screen. Also, if you want your menu to fade in the black surface needs to fade out so you have to decrease its alpha.

Although, this will still not work because you only draw the black surface during the loop, not your menu.

I don't know how is the rest of your code but you should draw the black surface after you drew the menu, all in one loop. You should have a variable that keeps the alpha of your black surface, and you stop displaying it when the alpha is 0.

Maybe this will help you.

---
Tags: pygame
---


# Question
Title: What is Windows' software rendering API?
We usually use OpenGL or DirectX to work with the GPU. If I want to use the CPU to render 2D/3D graphics, how does it work and what API can I use for it on Windows?

I know there is no benefit in using the CPU for graphics when GPUs exist, but I'd still like to understand how it works.

# Answer
GDI (Graphics Device Interface) is the software renderer under Windows. Basically any language/runtime platform under Windows that is *not* GPU-accelerated is going to be using GDI under the hood at some level. While Java AWT might use GDI directly via the C code that the Java runtime is written in, something like Flash running in Chrome will OTOH be using GDI if the desktop isn't GPU accelerated, vs DirectX if it is.

> I know that there is no benefit of using the CPU for this purpose, but only to understand the operation.

Not at all. It can be a lot easier to simply plot lines, pixels and images, than to know the ins and outs of GPU-based graphics programming. If you intend to write native code to access GDI directly, maybe check out the gdiplus lib, as outlined in this tutorial. Good luck!

**EDIT**: For accuracy, it may also be worth noting that there are CPU implementations of OpenGL; Mesa being the common example. So, strictly speaking, OpenGL does not exclude software rendering. But that's worth mentioning only if you really want to be pedantic!
> 7 votes

# Answer
Actually, starting with Windows 7, **Direct3D 11** is your answer. Of course the API defaults to using a GPU if you have one, but you can create a Direct3D device targeting the Windows Advanced Rasterization Platform (WARP), which is meant to be a high performance software rasterizer supporting the Direct3D API. You should not expect performance anywhere as close as that of a GPU, but it should be pretty good as far as CPU rasterization goes since it exists for Windows to support systems without hardware acceleration. Direct3D also provides a software reference rasterizer, but it's only designed for correctness and is terribly slow.

For more details on Direct3D 11 rasterizers, see the D3D\_DRIVER\_TYPE enumeration.

Edit: But can it run Crysis? Yes!
> 5 votes

# Answer
I wouldn't we so fast in jumping to "there's no benefit" conclusion. Whilst GPUs are absurdly fast at processing triangles, not all of the images are made using triangle rasterization!

For example, voxel-octree based renderers (used, for example, in medicine, for visualizing CT scans) often utilize multicore CPUs and write raw pixels basing on completely different algorithms. That can also be true for some raytracing algorithms.

In general, the simplest way to render using CPU is to output the data to, for example, a BMP file. You can also use OpenGL to create a window, and simply write raw pixel data to a texture and render over the whole screen.
> 2 votes

---
Tags: graphics, windows, software-rendering
---


# Question
Title: Visual effect with dark overlay gradient surrounding the center of the screen
How is it called, what is it used for, and what is the most common way to implement it?

I know these are three question in one, but since the first and second are just one-liners I decided to make them into one.

The following images are two screenshots showing the visual effect; (A) show the zones that are darker and (B) the normal zones

# Answer
Sounds like vignetting effect. You can easily accomplish this with a shader.
> 6 votes

---
Tags: graphic-effects
---


title: revolutejoint doesn't seem to rotate

text:
# Question
Title: revolutejoint doesn't seem to rotate
I have a revolute joint set up as such in libgdx + box2d:

```
            RevoluteJointDef rjd = new RevoluteJointDef();
        rjd.initialize(body1, body2, arm.getWorldCenter());
        rjd.motorSpeed = 100.0f;
        rjd.enableLimit = false;
        rjd.enableMotor = true;
        rjd.collideConnected = false;
        world.createJoint(rjd);

```

The joint displays and connects fine, but it never seems to turn or rotate. After some googling some people said to increase the motor speed, but I've turned that up to ridiculous values with still no rotations. The density of both body1 & body2 are set to 1.0f, so I'm not sure what else to do (both bodies are dynamic).

# Answer
I think you might need to set the value of the `maxMotorTorque` field. Here's an example of how different values enable the motor joint to function correctly.
> 1 votes

---
Tags: 2d, libgdx, box2d
---


# Question
Title: Cocos2d-x Finding if a CCPoint is inside a sprite rect
I'm afraid that I'm missing something. This is what I've done:

1. I've made a scene using layers (Gimp), then I've exported the layers with the image size, that way I thought would be more easy to add the images and have the offsets in the right way.
2. I made a spritesheet with TexturePacker, trimming the images.

Then I have in the plist file something like:

```
<dict>
   <key>frame</key>
   <string>{{1028,360},{326,382}}</string>
   <key>offset</key>
   <string>{-316,110}</string>
   <key>rotated</key>
   <false/>
   <key>sourceColorRect</key>
   <string>{{33,83},{326,382}}</string>
   <key>sourceSize</key>
   <string>{1024,768}</string>
</dict>

```

Then in my code I've made a CCSprite:

```
granero = CCSprite::createWithSpriteFrameName("04_Granero.png");
capaGrafica->addChild(granero);
pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, false);

```

And the ccTouchBegan:

```
bool Escena00::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    // This point has the touch location info
    CCPoint touchPoint = CCPoint(touch->getLocationInView().x, touch->getLocationInView().y);

    // Now I want to set a rect, where a little house in the screen is located
    CCRect *graneroRect = new CCRect(granero->getOffsetPosition().x, granero->getOffsetPosition().y,granero->getTextureRect().size.width,granero->getTextureRect().size.height);

    if (graneroRect->containsPoint(touchPoint))
    {
        CCLog("The little house in the left was touched");
    }

    return true;
}

```

If you take a look now to the plist extract that I've posted you'll read the "sourceColorRect" key. Those coords are the right numbers that I need to use to create my CCRect (33,83, 326, 382). With those numbers I've been able to correctly get the touch over the little house. However, I don't want to use those numbers with a "hard way". Using granero-\>getOffsetPositionX(), I get the "33" number, and using the "getTextureRect()" I can get the third and fourth numbers (size of the rect). The big issue is the getOffsetPositionY(), or any "y" coordinate. I can't read the "83" number. How can I solve this? Or what am I doing wrong?

Thanks a lot in advance.

# Answer
I'll answer my question, but @akg is the answer that guided me. I've made the code in cocos2d-x, and I didn't used boundingBox() method. Hope this helps someone, :) I didn't found something like this in other site, so I hope not be doing something wrong...

```
bool SceneGame::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    CCPoint touchPoint = CCDirector::sharedDirector()->convertToGL(touch->getLocationInView());

    touchPoint = littleHouse->convertToNodeSpace(touchPoint);

    CCRect *littleHouseRect= new CCRect(littleHouse->getOffsetPosition().x
                                    ,littleHouse->getOffsetPosition().y
                                    ,littleHouse->getTextureRect().size.width
                                    ,littleHouse->getTextureRect().size.height);

    if (littleHouseRect->containsPoint(touchPoint))
    {
        CCLog("The little house in the left was touched");
    }

    return true;
}

```
> 4 votes

# Answer
I think you need to make sure that you have the correct coordinate system. The best way is to use Cocos2d builtins to convert to the desired coordinate system and then check if the touch is within your desired bounding box:

```
- (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchStart = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];

    // Convert touch into the appropriate coordinate space of the sprite.
    touchStart = [yourSprite convertToNodeSpace:touchStart];

    // Handle block stash touch.
    CGRect boundingBox = [yourSprite boundingBox];
    if (CGRectContainsPoint(boundingBox, touchStart)) {
        // process touch...
    }
}

```
> 1 votes

# Answer
try this code:

```

bool Escena00::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    if (isNodeAtPoint(granero, touch->getLocation()) {
        CCLog("The little house in the left was touched");
    }

    return true;
}

bool Escena00::isNodeAtPoint(cocos2d::CCNode* node, cocos2d::CCPoint& touchLocation) {
    CCPoint nodePoint = node->convertToNodeSpace(touchLocation);
    CCRect rect = CCRectMake(0, 0, node->getContentSize().width, node->getContentSize().height);
    return rect.containsPoint(nodePoint);
}

```
> 0 votes

# Answer
If you wish to detect if a ccpoint in inside a sprite rectangle in Cocos2D-HTML5, checkout this quick snippet:

```
onTouchesEnded:function (touches, event) {

      for( n=0; n < touches.length; n++) {

         var touch = touches[n];

         if (cc.rectContainsPoint(this.yoursprite.getBoundingBox(), touch.getLocation()) == true) {
            // Sprite has been touched
         }
      }
}

```

Source: http://gamedevuniversity.com/cocos2d-html5-detect-if-sprite-has-been-touched/
> -1 votes

---
Tags: cocos2d-x
---


# Question
Title: If player leaves a rectangle take him back to his previous position
Okay, I'm making a game. The map contains all the blocks/buildings/structures etc... The map is bordered by a rectangle.

So what I want is if the player attempts to exit the rectangle he goes back to where he was. This way he cannot leave the map.

My attempt's output (right side), this one is perfect:

But the left side is not perfect:

My code:

public class Player extends GameObject{

```
BufferedImageLoader loader;
Texture tex = Game.getInstance();
BufferedImage image;
Animation playerWalkLeft;
private HealthBarManager healthBar;
private String username;
private int width;
private ManaBarManager manaBar;

public Player(float x, float y, ObjectID ID) {
    super(x, y, ID, null);
    loader = new BufferedImageLoader();
    playerWalkLeft = new Animation(5,tex.player[10],tex.player[11],tex.player[12],tex.player[13],tex.player[14],tex.player[15],tex.player[17],tex.player[18]);

}

public void tick(LinkedList<GameObject> object) {

    setX(getX()+velX);
    setY(getY()+velY);

    playerWalkLeft.runAnimation();

}

public void render(Graphics g) {

    g.setColor(Color.BLACK);

    FontMetrics fm = g.getFontMetrics(g.getFont());

    if(username != null) width = fm.stringWidth(username);
    if(username != null){
        g.drawString(username,(int) x-width/2+15,(int) y);
    }

    if(velX != 0){
        playerWalkLeft.drawAnimation(g, (int)x, (int)y);
    }else{
        g.drawImage(tex.player[16], (int)x, (int)y,  null);

    }

    g.setColor(Color.PINK);
    g.drawRect((int)x,(int)y,33,48);
    g.drawRect(0,0,(int)Game.getWalkableBounds().getWidth(), (int)Game.getWalkableBounds().getHeight());

}

@SuppressWarnings("unused")
private Image getCurrentImage() {
    return image;
}

public float getX() {
    return x;
}

public float getY() {
    return y;
}

public void setX(float x) {

    if(isPlayerInsideBoundry(x,y)){
        this.x = x;
    }

}

public void setY(float y) {
    this.y = y;
}

public float getVelX() {
    return velX;
}

public void setHealthBar(HealthBarManager healthBar){
    this.healthBar = healthBar;
}

public HealthBarManager getHealthBar(){
    return healthBar;
}

public float getVelY() {
    return velY;
}

public void setVelX(float velX) {
    this.velX = velX;
}

public void setVelY(float velY) {
    this.velY = velY;
}

public ObjectID getID() {
    return ID;
}

public void setUsername(String playerName) {
    this.username = playerName;

}

public String getUsername(){
    return this.username;

}

public void setManaBar(ManaBarManager manaBar) {
    this.manaBar = manaBar;

}

public ManaBarManager getManaBar(){
    return manaBar;
}

public int getLevel(){
    return 1;
}

public boolean isPlayerInsideBoundry(float x, float y){
    Rectangle boundry = Game.getWalkableBounds();

    if(boundry.contains(x,y)){
        return true;
    }

    return false;
}

public Rectangle getBounds(String boundType){
    if(boundType.equalsIgnoreCase("left")){
        return new Rectangle((int)x,(int)y,33/2,44/2);
    }
    return null;
}

```

}

# Answer
> 1 votes
I think what you should do is to calculate the new position of the player if he moves and then check, if the new position is inside the boudry. If the position is inside the boundry apply the new position to the player postion , if not just don't apply the new coordinates.

With this method it is not possible for the player to leave the boundry .

Hope I could help :)

# Answer
> 1 votes
Probably some of the easiest implementation would be something like this (pseudo code):

```
var lastValidPosition = player.getPosition();

...

if (positionIsValid(player.getPosition())) {
    lastValidPosition = player.getPosition;
}
else {
    player.setPosition(lastValidPosition);
}

```

Just note that this won't be the perfect strategy to restrain the player from entering specific areas based on the player's ability to move different distances between checks. For example, you might be 1 pixel away from the border, the player moves 2 pixels between checks, then you'd never be able to actually reach the border.

For such cases, you'd most likely want to either check smaller iterations or - in the case of some global boundary - just do some min/max comparison:

```
// Keep the player from passing the left boundary:
player.x = max(player.x, leftboundary);

// Keep the player from passing the right boundary:
player.x = min(player.x, rightboundary);

```

You could put both into one line of course, maybe even adding the actual movement code as well:

```
// Update player's x position
player.x = max(min(player.x + movementX, rightboundary), leftboundary);

```

# Answer
> 0 votes
When you want to keep this architecture as it is right now, you should create a copy of the position of the player everytime you verified it being legal and save it to a variable. Should a future check turn out to be illegal, you can use that saved value to reset to the last known legal position.

However, I would advise you to tackle the issue differently. Add a check into the setter\* of the position of your player character which checks whether or not the new position is valid. When it isn't, don't perform the set. You might want to signal this to the caller by throwing an exception.

\*You *are* using a `setPosition` method to change the position of the player-character and not just public variables, are you?

---
Tags: java
---


# Question
Title: OpenGL 4D textures with bilinear interpolation
I want to use and interpolated 4D texture in OpenGL, i.e. a texture that is accessed with a texture coordinate vector `(s, t, p, q)` and interpolated linearly in every texture coordinate.

The extension GL\_SGIS\_texture4D does exactly this. However, it is unsupported on literally every GPU I have access to.

If the was a `GL_TEXTURE_3D_ARRAY`, I guess I could sample the appropriate 2 layers of a 3D array texture with the `(s, t, p)` coordinates and then manually interpolate in the `q` coordinate. However, there are only "ordinary" `GL_TEXTURE_2D_ARRAY` texture arrays. A possible solution is to treat the texture array as 2D array of 2D texture, sample the appropriate 4 layers with `(s, t)` and then manually interpolate in `p` and `q`. This method is somewhat constrained by `GL_MAX_ARRAY_TEXTURE_LAYERS`. I am also afraid of the relatively large number of 2D texture fetches required to fetch a single 4D texture value.

Is there a simpler way of achieving 4D interpolated textures?

# Answer
About a decade ago, GL\_TEXTURE\_2D\_ARRAY wasn't widely available, people could only get an array of 2D textures using texture atlases.

This means that people stored the data in a faily big 2D texture and when they wanted to fetch a texel, they offseted the texture coordinates with a function of the slice value (the "depth").

This worked well, since the 2D textures were required to support at least 8192\*8192 texel resolution, and back then, people didn't really want to use textures bigger than 512\*512 texels.

On the current hardwares you need to use this trick to extend GL\_TEXTURE\_3D to 4 dimension. There's a little bit of differance though, 3D textures are required to support at least 1024\*1024\*256 texels, which kinda limits the texture size you can use. As far as I know, you can use 16 textures in a shader program simultaneously, which lets you store up to 2^32 texels. With this, you can implement a 256\*256\*256\*256 4D texture, and you get bilinear sampling in 3 coordinates, and you can do it manually for the forth coordinate.
> 7 votes

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


# Question
Title: theory behind rotation of a 3d cube using mouse
I want to rotate a 3d cube using mouse in python/pygame. Could someone explain the theory behind rotating a 3d cube by mouse?

I dont understand how angleX, angleY and angleZ are affected by mouse rotation on 2d. I know it involves sin,cos etc on the mouse's relative movement but dont know exactly about them.

# Answer
Start by learning how to rotate an object around an arbitrary axis, for this you might check out a simple rotation example someone has already implemented. Since the mouse only moves in two dimensions, and there are three dimensions available for rotation, you'll have to decide how you want map those two dimensions to three dimensions of rotation.

One of the simpler strategies is to use the camera axis to rotate the object. Essentially, regardless of the orientation of the cube, you will always rotate it as if it had the same axis orientation as your camera. So, moving the mouse left or right rotates around the y axis, up/down around the x axis. Sometimes people will implement something like holding a modifier key, then moving the mouse to rotate around the z axis.
> 1 votes

---
Tags: 3d, python, pygame
---


title: Draw a rotated rectfill in Allegro 4.2?

text:
# Question
Title: Draw a rotated rectfill in Allegro 4.2?
I'd like to use Matricies to transform primitive geometric shapes and draw them using the Allegro library using version 4.2 (I can not switch to 5.x just yet). This works fine for non-filled objects that are just a series of lines and any filled object that require explicitly telling allegro each point in the shape (triangles and polygons).

**However, I want to be able to draw a filled rectangle that is not axis-aligned.**

Is there an algorithm that given the pixel locations of the four corners of a rectangle, allow drawing individual lines to fill it? That would solve the problem for the time being.

# Answer
> 2 votes
This is by design: `rect()` is a specifically optimised version for axis-aligned rectangles.

I suggest doing two calls to `triangle()` instead, splitting your rectangle along one of its diagonals.

---
Tags: c++, graphics, algorithm, allegro
---


# Question
Title: How do I deform a procedurally generated terrain?
I was looking at this method of generating complex procedural terrains using the GPU: Generating Complex Procedural Terrains Using the GPU.

Has anyone had any luck actually using the algorithm ? If so how do I add the capability to create holes or caves in the terrain at runtime ?

I would think that all that would be needed is to convey to the GPU some information about where the density function should be ignored so as to create gaps or voids, probably via textures.

# Answer
The algorithm defined in the document you linked is for generating terrain on the GPU. The data isn't stored in an array that can be easily modified and re-rendered.

Without access to raw data you can manipulate, you're not going to be able to modify the terrain at run time. It's certainly possible to modify the code that generates the terrain, thus changing the terrain. However, it's far more difficult to see the relation between what's being generated on screen and lines of code, than it is to see a tool like a 3D paint brush modifying the terrain directly.

You could heavily modify this code to accept additional parameters that would allow you to create areas of modified density. However, if you're going to be storing data on the CPU side you may as well store everything there, and send the raw data to the GPU to be rendered.

Either way, modifying this existing code to allow for dynamic generation will be a fairly significant undertaking, and you might be better off pursuing alternative methods for procedural generation that don't rely so heavily on the GPU.
> 0 votes

---
Tags: terrain
---


title: Managing past/present game state

text:
# Question
Title: Managing past/present game state
I'm not sure if "game state" is the correct term, as my searching shows me a lot of results that are not relevant to my question. When I say "game state", I'm talking about the internal state of the game being played: what units are spawned, where they are located and headed, what players are playing, what their current scores are, etc. Everything that would get wiped out if you were to start a "new game".

That said...

I'm curious how other people or other games handle the issues of client and servers appearing to need access to more than one copy of the game state.

For example, the client's job is to accept game state updates from the server, and render them. However, the server updates are usually much slower than the client render speed, so the client needs two copies of the state information in order to interpolate between the two and make everything appear to be moving smoothly. I'm not sure how you would accomplish this without having the client hold two copies of the game state, copying the current to the previous whenever the server sends an update.

Likewise, the server needs to make decisions on the current game state, and apply changes. However, if it only has one copy of the game state, then any changes it has already made will influence future decisions. If two players shoot at each other at the same time, and the server processes one shot before the other and writes the result to the same game state, it'll see the second player as now being dead and unable to shoot. If it had two different game states, "current" and "next", any new changes (such as player death) would be written to the "next" state, and since they are both still alive in the "current" state, each shot would get processed and both players would end up dead, as expected.

However, having multiple game states creates a lot of other problems:

* Each copy of the game state could be very large, with many players playing, and hundreds or thousands of units moving around the game world. This would be a lot of data to be copying around just to keep multiple game states synchronized.
* While having two separate game states fixes the server problem of two entities killing each other at the same time, it presents new problems when an entity is newly-spawned. You might spawn an object into the world, and then want to immediately have it perform an action, or have other entities start to interact with it. Problem is, that new entity doesn't exist in the "current" game state, it only exists in the "next" game state. The server would have to wait until the next cycle, when the "next" state became the new "current" state, before the new entity was available for interaction.

I'm leaning towards just having a single state for the server, just for simplicity, but I don't see how to avoid keeping two copies for the client. How do other games handle this?

# Answer
glossary: what I call "sequence point" is a logical grouping of "when everything is done" and it's mostly synonymous with "each frame" or "each full AI cycle" depending on the game, etc...

No one sends an entire game's state at each sequence point (frame, heartbeat, whatever). Only changes are sent and, in games with large areas only changes local to the client are sent to that client.

The client uses its internal copy of the game running and the copy of the server's version of the game at time T exactly like you described. The client interpolates between the server time T and its internal time to keep things looking smooth. Note: "server's copy" is almost always just a few important variables, not everything.

Stop worrying about memory for the game state. Size of game state data is dwarfed by art/audio assets for every title except maybe Dwarf Fortress =)

To get around your simultaneous-but-not problem servers can run a simulation frame and store up commands to be executed at the end of processing. In this case both entities add "I shoot this other guy" and at the end the server shoots one and then the other with no logical sequence problems.

Spawning an enemy and activating it on the next sequence point is perfectly OK. In fact, that new enemy isn't actionable by *anyone* until the next cycle in the first place because it doesn't even exist in the current cycle.

The theme is to build up commands to be handled after all inputs from the current state have been processed independently. These commands set up conditions for the next cycle to process, whether the command adds a new enemy or kills something doesn't matter.
> 2 votes

# Answer
Nobody sends the entire "game state" over a network every frame.

Instead, only updates are sent.

For example:

Player 1 stopped at coordinates (-5.2, 21,8, 0.3)

Player 1 started walking in direction - current pos: (-5.2, 21,8, 0.3) dir: (1.0, 0.0, 0.0)

Player 1 started running in direction - current pos: (-4.2, 21,8, 0.3) dir: (1.0, 0.0, 0.0)

On the client side, you can track the target position, and the player will always be moving from the current position to the target position. Even if the target position changes, the player can continue to always move towards the target position.
> 0 votes

---
Tags: client-server, game-state
---


# Question
Title: Is there a way to use the RGB channels of a texture as the alpha channel when applying multitexturing using OpenGL ES 1.1?
I have been trying to get texture compression using ETC1 (specifically PKM files) working for some time now. I am trying to do this without having to upgrade to OpenGL ES 2 so I have been using multi-texturing.

I have the multi-texturing working now (finally) but the problem is that it is not behaving as one would expect and I think that I have figured out why. When creating the PKMs you end up with PKM with the color components only and one with the alpha component only. Problem is that the alpha PKM seems to be storing the alpha value in the RGB channels. Black seems to represent full transparency and white seems to represent full opaqueness.

My question is: Is there a way to combine and convert these RGB values into an alpha value when using multi-texturing? If not, then I don't see any options for using ETC1 and supporting alphas under OpenGL ES 1.1 (please correct me if I am wrong).

# Answer
I assume you are interested in the alpha channel for the purpose of *alpha blending*. Off the top of my head, I can think of one solution to this problem, but it is not going to perform well.

The fundamental problem here is that you have an RGB texture; it has a constant alpha of **1.0**. You ***can*** use texture combiners to pre-multiply your RGB texture (`Texture0`) by the other texture with alpha encoded into RGB (`Texture1`), but that only solves *half* of your problem.

```
Texture0 = RGB
Texture1 = aaa

Texture Combiner:  Texture0.rgb * Texture1.rgb  =  RaGaBa

```

### Traditional alpha-blending (GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA):

```
 DstColor  =  SrcColor * SrcColor.a   +   DstColor * (1.0 - SrcColor.a)

```

### Pre-multiplied alpha-blending (GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA):

```
 DstColor  =  SrcColor * 1.0          +   DstColor * (1.0 - SrcColor.a)

```

You eliminated the need for an alpha channel in the first half of the blend function, but it still remains in the second half.

---

### You can do this, though I would not recommend it:

```
 1.  Perform one pass applying Texture1
 1.1 Blend Function:  GL_ZERO, GL_ONE_MINUS_SRC_COLOR

     *** Framebuffer:   DstColor * (1.0 - SrcColor.a)

 2.  Perform a second pass applying the combined Texture0*Texture1
 2.1 Blend Function:  GL_ONE,  GL_ONE

     *** Framebuffer:   SrcColor * SrcColor.a   +   DstColor * (1.0 - SrcColor.a)

```

This will produce the desired end result, but it eats a lot of memory bandwidth... the very thing you were trying to conserve by using ETC1 texture compression in the first place. Honestly, the only performance-friendly solution is probably going to be to use ES 2.0 and shaders.
> 1 votes

---
Tags: android, opengl-es, multitexturing
---


# Question
Title: Why do we use the Pythagorean theorem in game physics?
I've recently learned that we use Pythagorean theorem a lot in our physics calculations and I'm afraid I don't really get the point.

Here's an example from a book to make sure an object doesn't travel faster than a `MAXIMUM_VELOCITY` constant in the horizontal plane:

```
MAXIMUM_VELOCITY = <any number>;
SQUARED_MAXIMUM_VELOCITY = MAXIMUM_VELOCITY * MAXIMUM_VELOCITY;

function animate(){
    var squared_horizontal_velocity = (x_velocity * x_velocity) + (z_velocity * z_velocity);

    if( squared_horizontal_velocity <= SQUARED_MAXIMUM_VELOCITY ){

        scalar = squared_horizontal_velocity / SQUARED_MAXIMUM_VELOCITY;

        x_velocity = x_velocity / scalar;
        z_velocity = x_velocity / scalar;
    }
}

```

Let's try this with some numbers:

**An object is attempting to move 5 units in x and 5 units in z. It should only be able to move 5 units horizontally in total!**

```
MAXIMUM_VELOCITY = 5;
SQUARED_MAXIMUM_VELOCITY = 5 * 5;
SQUARED_MAXIMUM_VELOCITY = 25;

function animate(){
    var x_velocity = 5;
    var z_velocity = 5;

    var squared_horizontal_velocity = (x_velocity * x_velocity) + (z_velocity * z_velocity);
    var squared_horizontal_velocity = 5 * 5 + 5 * 5;
    var squared_horizontal_velocity = 25 + 25;
    var squared_horizontal_velocity = 50;

//  if( squared_horizontal_velocity <= SQUARED_MAXIMUM_VELOCITY ){
    if( 50 <= 25 ){
        scalar = squared_horizontal_velocity / SQUARED_MAXIMUM_VELOCITY;
        scalar = 50 / 25;
        scalar = 2.0;

        x_velocity = x_velocity / scalar;
        x_velocity = 5 / 2.0;
        x_velocity = 2.5;

        z_velocity = z_velocity / scalar;
        z_velocity = 5 / 2.0;
        z_velocity = 2.5;

        // new_horizontal_velocity = x_velocity + z_velocity
        // new_horizontal_velocity = 2.5 + 2.5
        // new_horizontal_velocity = 5
    }
}

```

Now this works well, but we can do the same thing without Pythagoras:

```
MAXIMUM_VELOCITY = 5;

function animate(){
    var x_velocity = 5;
    var z_velocity = 5;

    var horizontal_velocity = x_velocity + z_velocity;
    var horizontal_velocity = 5 + 5;
    var horizontal_velocity = 10;

//  if( horizontal_velocity >= MAXIMUM_VELOCITY ){
    if( 10 >= 5 ){
        scalar = horizontal_velocity / MAXIMUM_VELOCITY;
        scalar = 10 / 5;
        scalar = 2.0;

        x_velocity = x_velocity / scalar;
        x_velocity = 5 / 2.0;
        x_velocity = 2.5;

        z_velocity = z_velocity / scalar;
        z_velocity = 5 / 2.0;
        z_velocity = 2.5;

        // new_horizontal_velocity = x_velocity + z_velocity
        // new_horizontal_velocity = 2.5 + 2.5
        // new_horizontal_velocity = 5
    }
}

```

Benefits of doing it without Pythagoras:

1. Less lines
2. Within those lines, it's easier to read what's going on
3. ...and it takes less time to compute, as there are less multiplications

Seems to me like computers and humans get a better deal without Pythagorean theorem! However, I'm sure I'm wrong as I've seen Pythagoras' theorem in a number of reputable places, so I'd like someone to explain me the benefit of using Pythagorean theorem to a maths **newbie**.

Does this have anything to do with unit vectors? To me a unit vector is when we normalize a vector and turn it into a fraction. We do this by dividing the vector by a larger constant. I'm not sure what constant it is. The total size of the graph? Anyway, because it's a fraction, I take it, a unit vector is basically a graph that can fit inside a 3D grid with the x-axis running from -1 to 1, z-axis running from -1 to 1, and the y-axis running from -1 to 1. That's literally everything I know about unit vectors... not much :P And I fail to see their usefulness.

Also, we're not really creating a unit vector in the above examples. Should I be determining the scalar like this:

```
// a mathematical work-around of my own invention. There may be a cleverer way to do this! I've also made up my own terms such as 'divisive_scalar' so don't bother googling
var divisive_scalar = (squared_horizontal_velocity / SQUARED_MAXIMUM_VELOCITY);
var divisive_scalar = ( 50 / 25 );
var divisive_scalar = 2;

var multiplicative_scalar = (divisive_scalar / (2*divisive_scalar));
var multiplicative_scalar = (2 / (2*2));
var multiplicative_scalar = (2 / 4);
var multiplicative_scalar = 0.5;

x_velocity = x_velocity * multiplicative_scalar
x_velocity = 5 * 0.5
x_velocity = 2.5

```

Again, I can't see why this is better, but it's more "unit-vector-y" because the multiplicative\_scalar is a unit\_vector? As you can see, I use words such as "unit-vector-y" so I'm really not a maths whiz! Also aware that unit vectors might have nothing to do with Pythagorean theorem so ignore all of this if I'm barking up the wrong tree.

I'm a very visual person (3D modeller and concept artist by trade!) and I find diagrams and graphs really, really helpful so as many as humanely possible please!

# Answer
> 105 votes
Your Pythagoras-free code doesn't compute a length as we normally think of it.

Normally in 3D games we model the world as a Euclidean space, and we use a Euclidean distance metric (also known as Pythagorean Theorem) to calculate the total length of a vector v with components v.x and v.y. Namely:

```
EuclideanLength(v) = sqrt(v.x * v.x + v.y * v.y)

```

(Note that this square root is missing in your sample code above, which is why the two approaches appear to give the same answer. More on that shortly...)

The code you've described uses the Manhattan distance metric:

```
ManhattanLength(v) = abs(v.x) + abs(v.y)

```

(Although you didn't include the absolute values, which may make it behave unexpectedly for negative numbers)

It's easy to see that these two distance functions match-up when v.x or v.y is zero, and we're only moving along one axis. How do they compare though when we move diagonally?

Let's say v.x = v.y = 1. How long is this vector (equivalently, how fast is the velocity it describes)?

```
Euclidean                              Manhattan

sqrt(v.x*v.x + v.y * v.y)              abs(v.x) + abs(v.y)
sqrt(1 * 1 + 1 * 1)                    abs(1) + abs(1)
sqrt(2)                                1 + 1
1.414...                               2

```

You can see these metrics don't actually agree for diagonal lines.

Let's plot on a graph the set of points that each metric says are a distance of 1 away from the origin:

Our familiar Euclidean metric is the red circle. This is the set of all points x,y such that x^2 + y^2 = 1. You can see that it's rotationally-symmetric, and that's why we like it: it neatly represents the idea that distance doesn't change with direction.

The Manhattan metric is the blue diamond. Not a great match for our intuitive idea of distance - but that doesn't make it bad. In many tile-based games where you move in discrete steps in the four cardinal directions, the Manhattan metric gives the correct distance between points (in terms of "how many moves will it take to get there?")

Finally, I threw in the Chebyshev metric for fun - it's the green square:

```
ChebyshevLength(v) = max(abs(v.x), abs(v.y))

```

It's also good for tile-based games, where you're allowed to move on diagonals. A King in Chess moves according to the Chebyshev metric.

I hope that clears up what the difference is between typical Pythagorean-style code and the example you provided above.

# Answer
> 12 votes
Without Pythagoras, you are bound to a fixed velocity on each axis. You have a x-speed, an y-speed and (in a 3d world) a z-speed which are all independent of each other. Any movement will be aligned to these perpendicular axis.

However, with Pythagoras, you have a speed which can be constant in any angle. That allows you to make the grid disappear and have objects move with a constant speed in any possible direction.

The area an object travels in one second looks this without Pythagoras (f.e. Chebyshev metric):

And this with Pythagoras:

The latter usually seems much more natural in many cases.

---
Tags: mathematics, physics
---


# Question
Title: Procedural Generation of tile-based 2d World
I am writing a 2d game that uses tile-based top-down graphics to build the world (i.e. the ground plane). Manually made this works fine.

Now I want to generate the ground plane procedurally at run time. In other words: I want to place the tiles (their textures) randomised on the fly. Of course I cannot create an endless ground plane, so I need to restrict how far from the player character (on which the camera focuses on) I procedurally generate the ground floor.

My approach would be like this: I have a 2d grid that stores all tiles of the floor at their correct x/y coordinates within the game world. When the players moves the character, therefore also the camera, I constantly check whether there are empty locations in my x/y map within a max. distance from the character, i.e. cells in my virtual grid that have no tile set. In such a case I place a new tile there.

Therefore the player would always see the ground plane without gaps or empty spots.

I guess that would work, but I am not sure whether that would be the best approach.
Is there a better alternative, maybe even a best-practice for my case?

# Answer
To first generate the tiles, I would use Perlin Noise to determine where to place which tiles, and then render them accordingly. As for how to render them, I would see How'd they do it: Millions of tiles in Terraria

> You could keep track of the tiles that are on the screen, and only loop through (and render) those. Depending on things like the size of your tiles, and screen size, this could easily cut down the amount of tiles you need to loop through, and that would save quite a bit of processing time.
>
> Finally, and perhaps the best option (most large world games do this), is to split your terrain into regions. Split the world into chunks of, say, 512x512 tiles, and load/unload the regions as the player gets close to, or further away from, a region. This also saves you from having to loop through far away tiles to perform any sort of 'update' tick.

I think that thedaian does an excellent job of explaining the pros of this technique the cons of using what you planned and this combined with perlin noise can create a "endless ground plane" that you wanted to shy away from at first.

**EDIT**

As Eejin pointed out, instead of perlin noise I would use Simplex Noise as it is the successor, and more effecient and addresses some of the limitations.
> 4 votes

---
Tags: 2d, tiles, procedural-generation
---


# Question
Title: Unity-Animation parameters are not being set
I have the following animation controller:

with two parameters of `walkingSpeed` and `Jump`. I have the following code which should change the values:

```
animator.SetFloat("walkingSpeed",0.9f);
animator.SetBool("Jump",true);

```

and animator is the correctly referenced animator object. However the values that the parameters are set to do not appear to change in the animator window, nor do they appear to impact what is happening on the screen. However they do seem to impact the values obtained when doing the following:

`animator.GetFloat("walkingSpeed");`

The animator consists of the shown blend tree, which works correctly and is always active, however due to the values not being changed it does not blends, and always acts as if the value with which it blends (`walkingSpeed` is 0).

What is going on?

# Answer
> 2 votes
It sounds like you have two problems:

1. In order to see the values changing, you must have the GameObject that is using that Animator selected in the Scene view.
2. There is likely something wrong with your code or Animator that is preventing it from working as you expect it to. You have not provided enough details to determine what is causing that.

---
Tags: unity, animation, movement, mecanim
---


# Question
Title: What file types should I exclude from my game's source control repository?
I have started working on a personal project using Unity with a friend and we've set up our own source control system.

I am aware of the fact that there are many types of files, namely those that are generated locally when you build (for example, Visual Studio files) and those that are specific to your particular machine that should not be added to source control, but I'm not exactly sure what these file types are.

I don't want to exclude any generated files I should be including, such as .meta files.

Would someone be able to list all, or at least all of the common file types that should not be added to version control, specifically for a Unity project?

# Answer
With the current version of Unity, just check in anything in the Assets folder and ProjectSettings folder. Don't check in anything under Library, or at the top level.
> 10 votes

# Answer
A good reference for this kind of lists is GitHub's gitignore templates. The Unity-specific list is here.

And if you feel that something is missing, make a pull request!
> 8 votes

# Answer
The file *type* is less important that the file's purpose and origin; as you said, anything that can be generated from the source files under version control (usually) has no business being included in the repository itself.

Similarly, anything user-specific, such as settings or configuration files, should be excluded.

Beyond that it's really up to you and your project.
> 5 votes

# Answer
You can take a look at my Unity project, Radius, on GitHub as an example. Or checkout the `Unity.gitignore` file in the official GitHub gitignore repo.

There is also a nice guide by Damien Mayance on his website about *Git and Unity projects*

Make sure you check in your `.meta` files as this is what Unity uses to reference each asset. You can make them unhidden in your OS by going to `Edit->Project Settings->Editor` and changing `Version Control` to `Visible Meta Files`.

If you are storing your unity project in a folder called `UnityProjectName`, this is what your .gitignore should look like. If you just have the Unity project folder as the root of the GitHub repo, just remove the `UnityProjectName/` from each path below.

### `.gitignore`

```
# Ignore unneeded Unity files
# --------------------------------------------------
UnityProjectName/Temp/
UnityProjectName/obj/
UnityProjectName/Library/

UnityProjectName/*.csproj
UnityProjectName/*.unityproj
UnityProjectName/*.sln

# Ignore Custom Builds
# --------------------------------------------------
UnityProjectName/[Bb]uilds/

```
> 3 votes

# Answer
I don't know about unity but you mentioned visual studio. There you can usually exclude the bin and obj folders in the project folders (in some project types, the bin folder also stores assemblies from included projects, but I think this only applies for certain type of web projects).

Also do not check in the "*.csproj.user" and "*.suo" files. Those two types include user settings. If you check those in, then all user settings will be reflected on the other machines, when you update the source. This is quite annoying, as those settings are not build or project relevant but more to configure the ui, editor etc for each developers individual needs.
> 1 votes

---
Tags: unity, version-control
---


# Question
Title: How to do a genetic algorithm's chromosome which controls movements
First I would like to inform you that I'm french and 15 so my english is not very good.

I've read some articles about genetic algorithms (GA) and since I discovered the HTML5's canvas element, I can create an AI with animations, so I've created two little experiments to enjoy seeing robots moving on their own but first I'll present you the second one because it's easier :

The aim of this experiment for the white circles is to touch the red square and instead of using coordinate calculations, like I said, I would like to create an autonomous algorithm which evolves in the time.

I give to the circles their relative coordinates to the red square like so they know exactly where they are and their speed that they will be able to change.

So to do it I need a solution to create a chromosome that contains moving informations but since the x and y positions are randomly assigned to circles and the square, if a member of the population has the good solution, it's only for this particular configuration.

I'm searching how to make them know that if the x coordinate is inferior to 0, they have to go left without creating a function like this `if(firstGeneInfo == 2){bot[i].x += redSquare.x - bot[i].x;}`.

This is a screenshot of the canvas :

And the jsfiddle link but movements are random for the moment.

http://jsfiddle.net/KLn8r/1/

The other experiment is a sort of "survival game" where the red square has to last, first I created it as a human-AI experience but I prefer to do an AI vs AI game, and so implement a genetic algorithm but in this case it is a lot more complicated because they are multiple enemies, I thought that with informations like enemies's coordinates and speed once again, the red square would developp kind of a strategy. The enemies are controlled by an algorithm and there is no need to do a GA for them.

A screenshot :

and the jsfiddle link : http://jsfiddle.net/f6ghk/

If you've read all this, I already thank you ! I'm not asking for the full working code but just the principle of a chromosome that works in theses cases.

I hope that my english wasn't to horrible to read and that for my problems I don't need a simulated neural network because it seems a bit complicated to me.

Thank you for your answers !

# Answer
> 1 votes
How it works in real life is that it is completely random. If the mutation is good, the organism can survive and reproduce. If the mutation is bad, the organism and it's genome will usually die out.

With that in mind, with every generation, add random traits to the offspring and if it is beneficial, allow it to pass it's genes to the next generation with a random chance of mutation.

If you are using sexual reputation, select 2 random ones and randomly select different traits from each other, but give the more effective organisms a higher chance at reproducing.

This would look something like this in the code:
(done in pseudo code)

```
function onNextGen() {
        for (organism in organismArray) {
            organism.giveTrait(Math.random());
        }
    }
}

```

or for sexual reproduction:

```
function onNextGen() {
    for (organism in maleOrganismArray) {
        organism.addTrait(Math.random());
        nextGenOrganismsArray[n] = new Organsim(organism + femaleOrganismArray[Math.random()];
    }
}

```

This is a poor example but I hope it displays my point.

# Answer
> 1 votes
(First, what you're doing is awesome! I love GA.)

I haven't read every line of your code, yet (I intend to), but ain't what you're looking for the fitness function? I mean, it's the fitness function that will tell how valuable are de chromosomes so you can cross then in the next generation... Anyway, really not sure. Hope to understand you problem better soon.

Perhaps Jeff Heaton implementation might help. His stuff is awesome! There is bunch of them at: JavaScript Machine Learning and Neural Networks with Encog

Keep it up and good luck...

# Answer
> -1 votes
I'm not really seeing a question. What is your exact goal? To find the shortest path?

Genetic Algorithm's require you to have fitness function. To define one and to have it be meaningful you need 2 things. 1 a set of possible options and a fitness function that analyzes them. This is often done with a randomizer that randoms a certain option and each time you call the fitness function you attribute a positive or negative bias to specific actions. If done correctly you get a near optimal sequence of data / events. The problem you are have is what is known as the traveling salesman problem. It has no real 'best' solution, but good algorithms like A\* exist for solving it.

Without a more refined question it is difficult to say anything because you are showing us stuff without a real concrete question. Do you simply want to try to tackle the traveling salesman problem with a genetic algorithm? Are you placing any line of sight limitations on your actor?

---
Tags: javascript, ai, html-canvas, evolution
---


# Question
Title: Most efficient way to implement delta time
Here's one way to implement delta time:

```
/// init ///
var duration = 5000,
    currentTime = Date.now();

// and create cube, scene, camera ect

//////

function animate() {
/// determine delta ///
    var now = Date.now(),
        deltat = now - currentTime,
        currentTime = now,
        scalar = deltat / duration,
        angle = (Math.PI * 2) * scalar;
//////

/// animate ///
    cube.rotation.y += angle;
//////

/// update ///
    requestAnimationFrame(render);
//////
}

```

Could someone confirm I know how it works? Here what I think is going on:

Firstly, we set duration at 5000, which how long the loop will take to complete in an ideal world.

With a computer that is slow/busy, let's say the animation loop takes twice as long as it should, so 10000:

When this happens, the scalar is set to 2.0:

```
scalar = deltat / duration
scalar = 10000 / 5000
scalar = 2.0

```

We now times all animation by twice as much:

```
angle = (Math.PI * 2) * scalar;
angle = (Math.PI * 2) * 2.0;
angle = (Math.PI * 4) // which is 2 rotations

```

When we do this, the cube rotation will appear to 'jump', but this is good because the animation remains real-time.

With a computer that is going too quickly, let's say the animation loop takes half as long as it should, so 2500:

When this happens, the scalar is set to 0.5:

```
scalar = deltat / duration
scalar = 2500 / 5000
scalar = 0.5

```

We now times all animation by a half:

```
angle = (Math.PI * 2) * scalar;
angle = (Math.PI * 2) * 0.5;
angle = (Math.PI * 1) // which is half a rotation

```

When we do this, the cube won't jump at all, and the animation remains real time, and doesn't speed up. *However, would I be right in thinking this doesn't alter how hard the computer is working? I mean it still goes through the loop as fast as it can, and it still has render the whole scene, just with different smaller angles! So this a bad way to implement delta time, right?*

Now let's pretend the computer is taking exactly as long as it should, so 5000: When this happens, the scalar is set to 1.0:

```
angle = (Math.PI * 2) * scalar;
angle = (Math.PI * 2) * 1;
angle = (Math.PI * 2) // which is 1 rotation

```

When we do this, everything is timsed by 1, so nothing is changed. We'd get the same result if we weren't using delta time at all!

**My questions are as follows**

1. Mostly importantly, have I got the right end of the stick here?
2. How do we know to set the duration to 5000 ? Or can it be any number?
3. I'm a bit vague about the "computer going too quickly". Is there a way loop less often rather than reduce the animation steps? Seems like a better idea.
4. Using this method, do all of our animations need to be timesed by the scalar? Do we have to hunt down every last one and times it?
5. Is this the best way to implement delta time? I think not, due to the fact the computer can go nuts and all we do is divide each animation step and because we need to hunt down every step and times it by the scalar. Not a very nice DSL, as it were.
6. So what is the best way to implement delta time?
7. Below is one way that I do not really get but may be a better way to implement delta time. Could someone explain please?

---

```
// Globals
INV_MAX_FPS = 1 / 60;
frameDelta = 0;
clock = new THREE.Clock();

// In the animation loop (the requestAnimationFrame callback)…
frameDelta += clock.getDelta(); // API: "Get the seconds passed since the last call to this method."

while (frameDelta >= INV_MAX_FPS) {
    update(INV_MAX_FPS); // calculate physics
    frameDelta -= INV_MAX_FPS;
}

```

How I think this works:

Firstly we set INV\_MAX\_FPS to 0.01666666666 How we will use this number number does not jump out at me. We then intialize a frameDelta which stores how long the last loop took to run.

Come the first loop frameDelta is not greater than INV\_MAX\_FPS so the loop is not run (0 \>= 0.01666666666). So nothing happens.

Now I really don't know what would cause this to happen, but let's pretend that the loop we just went through took 2 seconds to complete:

We set frameDelta to 2:

```
frameDelta += clock.getDelta();
frameDelta += 2.00

```

Now we run an animation thanks to update(0.01666666666). Again what is relevance of 0.01666666666?? And then we take away 0.01666666666 from the frameDelta:

```
frameDelta -= INV_MAX_FPS;
frameDelta = frameDelta - INV_MAX_FPS;
frameDelta = 2 - 0.01666666666
frameDelta = 1.98333333334

```

So let's go into the second loop. Let's say it took 2(? Why not 2? Or 12? I am a bit confused):

```
frameDelta += clock.getDelta();
frameDelta = frameDelta + clock.getDelta();
frameDelta = 1.98333333334 + 2
frameDelta = 3.98333333334

```

This time we enter the while loop because 3.98333333334 \>= 0.01666666666

We run update

We take away 0.01666666666 from frameDelta again:

```
frameDelta -= INV_MAX_FPS;
frameDelta = frameDelta - INV_MAX_FPS;
frameDelta = 3.98333333334 - 0.01666666666
frameDelta = 3.96666666668

```

Now let's pretend the loop is super quick and runs in just 0.1 seconds and continues to do this. (Because the computer isn't busy any more). Basically, the update function will be run, and every loop we take away 0.01666666666 from the frameDelta untill the frameDelta is less than 0.01666666666.

And then nothing happens until the computer runs slowly again? Could someone shed some light please? Does the update() update the scalar or something like that and we still have to times everything by the scalar like in the first example?

# Answer
My answer is not specific to three.js. I'm a c and an OpenGL iOS coder. But I do think the techniques would apply.

Your estimation of what your code sample does looks right to me. But as some commenters have said, it doesn't seem like the best method to handle time in a game loop.

For example, regarding the scalar being 2.0 you said "When we do this, the cube rotation will appear to 'jump', but this is good because the animation remains real-time." This is true but also realize that there's many values in between and that it could be even higher than double. If your displayLoop is 1/60 of a second, even double is still 1/30th and most people might not even notice that much of a "jump". Much below that though and they would. But there are many steps in between. In real world your fps ***could*** fluctuate between 60 on less complex rendering and 30 on more complex renderings and in my games I think this is ok. If someone is on a slower machine it might be even less and appear much more jumpy.

But you are absolutely correct that you want to use a method that uses real time to determine how long things take to happen, and not "computer cycles".

The way I do it (in pseudo code) is:

First have these long or double floats as globals: timeThisRound, delta (timeDelta), timeLastRound. Then times with your display sync call something like this:

```
displayLoop() {
    timeThisRound = date();
    delta = timeThisRound - timeLastRound;
    updateElementWithDelta(delta);
    updateBasedOnTime();
    timeLastRound = timeThisRound;
    // draw elements and swap buffers
}

```

In iOS we have a way to sync the calling of a method or function with the display loop - which we target 60fps. But if you can't do that you could do it a different way, like attempting to call it every 0.016667 seconds. I don't know how WebGL and three.js handles the display loop.

The `date()` function above needs to be something that accurately returns time in seconds and fractions of a second. Then `delta` will also be in fractions of a second between this call of `displayLoop` and the last time it was called. So if your displayLoop function is being called 1/60th of a seconds, as you said, that would be 0.016667. And if something happens to make it skip a cycle or take a little longer then that number would be higher.

A couple of notes here:

1. Don't call date() more than once in the loop or in other functions. Have `timeThisRound` be the master clock. This way all movement and animation will be timed to the same clock.
2. In here I also often cap delta at .5 seconds or so to prevent huge jumps in animation. If something makes the screen update that slowly the game will slow down but I personally prefer this to animations jumping out of control. Example if a call comes in on a phone you don't want them to come back from the call with a crashed ship and "you lost" on the screen.

Back to the method - if an object is traveling 5 pixels per second you could set `velocity = 5;`

Then in the updateGameWithDelta() you'd do:

```
position = position + velocity*delta;

```

Since `delta` is in parts of a second and `velocity` is in pixels per second, multiplying them together will give you the amount of pixels to move for that time slice. Just like hours * miles per hour gives you miles traveled in that number of hours.

You can also do moves based on time alone, which I do a lot.

So if you have a move you want to take 2 seconds you could first set up globals:

```
duration=2.0;
startPosition=123.0;
endPosition=456.0;
startTime= timeThisRound + 1.0;

```

I code in c so put these in a data struct for the object. Then in updateBasedOnTime() you'd do:

```
percentThruMove = (timeThisRound - startTime) / duration;

```

`(timeThisRound - startTime)` tells you many things. First if the move hasn't started yet it will be less than 0, so the position would need to stay at the `startPosition`. if it's bigger than duration the move should have already ended and it should be at the ending position. Also in that case you can stop worrying about animating that object. In between the two it is a percentage through the move.

So you can clamp it to 0-1, and then set the position:

```
clamp(percentThroughMove, 0,1);
travelDistance = endPosition - startPosition;
currentPosition = startPosition + percentThroughMove * travelDistance;

```

I also usually set up a trigger to end the move checking. So instead of using a simple clamp function I make my own with ifs:

```
if(percentThroughMove<0.0)
    currentPos = startPos;
elseIf(percentThroughMove>1.0) {
    currentPos = endPos;
    moving = no;
}
else {
    travelDistance = endPosition - startPosition;
    currentPosition = startPosition + percentThroughMove * travelDistance;
}

```

The cool thing with this method is that you also have an opportunity to use a tween instead of a linear move. Like instead of `*percent` do `*percent*percent` and the move will ease in.
> 2 votes

---
Tags: mathematics, animation, three.js
---


# Question
Title: LibGDX: Smooth movement on a grid based game
I'm making a game with LibGDX where the player is on a grid (like a Chess board). For now, I'm moving the player by teleporting him 16px in a direction. I'd like to use the delta time to make smooth movements, I want the character to move to 16px in a direction smoothly and when he's arrived, he stops moving.

Here's the code of my Player's Class:

```
public Player(Sprite sprite){
    super(sprite);
    setX(16*5);
    setY(16*5);
}

@Override
public void draw(Batch batch){
    update(Gdx.graphics.getDeltaTime());
    super.draw(batch);
}

public void update(float deltaTime) {
}

public void move(int direction){

    switch(direction){
    case UP:
        setPosition(getX(), getY()+16);
        break;
    case DOWN:
        setPosition(getX(), getY()-16);
        break;
    case LEFT:
        setPosition(getX()-16, getY());
        break;
    case RIGHT:
        setPosition(getX()+16, getY());
        break;
    }
}

public boolean canMove(int direction){
    if(direction == UP){
        if(getY() == 160-getHeight())
            return false;
    }
    else if(direction == DOWN){
        if(getY() == 0)
            return false;
    }
    else if(direction == RIGHT){
        if(getX() == 160-getWidth())
            return false;
    }
    else if(direction == LEFT){
        if(getX() == 0)
            return false;
    }
    return true;
}

```

# Answer
The `lerp` method from `Vector2` seems to be what you are looking for.

From the documentation:

> Linearly interpolates between this vector and the target vector by alpha which is in the range \[0,1\]. The result is stored in this vector.

So basically, you need to calculate where the player should be at the end of the movement:

> targetPosition = new Vector2(/\* calculate the target position here regarding the targetted cell \*/)

And then you `lerp` (interpolates linearly) the player current position towards the previously calculated target position.

```
//in update method
alpha = calculateAlpha();
playerPosition.lerp(targetPosition, alpha)

```

Last step is to calculate the `alpha`. As the documentation state:

```
[...] alpha which is in the range [0,1].

```
* A `alpha` of 0 means that the movement has not started yet
* A `alpha` of 0.5 means that the player is half way from reaching the `targetPosition`
* A `alpha` of 1 means that we are done with our movement and the player has reached the `targetPosition` (`playerPosition` = `targetPosition`).

One way to calculate it here would be to use time.

```
float calculateAlpha() {
    _currentTime += Gdx.graphics.getDeltaTime();
    return MOVETOCELL_TIME / _currentTime;
}

```

In `_currentTime` we store the time **in seconds** since the player has started moving, we increment it each frame by the time in seconds since the last frame (the delta time). Then we calculate and return our alpha by dividing the total time to move by one cell (**in seconds**) by `_currentTime`.

When the movement is done, you should not forget to reset `_currentTime` to 0.
> 4 votes

---
Tags: java, libgdx, movement
---


title: Problem with boundary collision

text:
# Question
Title: Problem with boundary collision
**The problem:** When the player hits the left boundary he stops (this is exactly what I want), when he hits the right boundary. He continues until his rectangle's left boundary meets with the right boundary.

**Outcome:** https://www.youtube.com/watch?v=yuJfIWZ\_LL0&feature=youtu.be

**My Code**

```
public class Player extends GameObject{

BufferedImageLoader loader;
Texture tex = Game.getInstance();
BufferedImage image;
Animation playerWalkLeft;
private HealthBarManager healthBar;
private String username;
private int width;
private ManaBarManager manaBar;

public Player(float x, float y, ObjectID ID) {
    super(x, y, ID, null);
    loader = new BufferedImageLoader();
    playerWalkLeft = new Animation(5,tex.player[10],tex.player[11],tex.player[12],tex.player[13],tex.player[14],tex.player[15],tex.player[17],tex.player[18]);

}

public void tick(LinkedList<GameObject> object) {

    setX(getX()+velX);
    setY(getY()+velY);
    playerWalkLeft.runAnimation();

}

public void render(Graphics g) {

    g.setColor(Color.BLACK);

    FontMetrics fm = g.getFontMetrics(g.getFont());

    if(username != null) width = fm.stringWidth(username);
    if(username != null){
        g.drawString(username,(int) x-width/2+15,(int) y);
    }

    if(velX != 0){
        playerWalkLeft.drawAnimation(g, (int)x, (int)y);
    }else{
        g.drawImage(tex.player[16], (int)x, (int)y,  null);

    }

    g.setColor(Color.PINK);
    g.drawRect((int)x,(int)y,33,48);
    g.drawRect(0,0,(int)Game.getWalkableBounds().getWidth(), (int)Game.getWalkableBounds().getHeight());

}

@SuppressWarnings("unused")
private Image getCurrentImage() {
    return image;
}

public float getX() {
    return x;
}

public float getY() {
    return y;
}

public void setX(float x) {
    Rectangle gameBoundry = Game.getWalkableBounds();
    if(x >= gameBoundry.getMinX() && x <= gameBoundry.getMaxX()){
        this.x = x;
    }

}

public void setY(float y) { //IGNORE THE SetY please.
            this.y = y;
}

public float getVelX() {
    return velX;
}

public void setHealthBar(HealthBarManager healthBar){
    this.healthBar = healthBar;
}

public HealthBarManager getHealthBar(){
    return healthBar;
}

public float getVelY() {
    return velY;
}

public void setVelX(float velX) {
    this.velX = velX;
}

public void setVelY(float velY) {
    this.velY = velY;
}

public ObjectID getID() {
    return ID;
}

public void setUsername(String playerName) {
    this.username = playerName;

}

public String getUsername(){
    return this.username;

}

public void setManaBar(ManaBarManager manaBar) {
    this.manaBar = manaBar;

}

public ManaBarManager getManaBar(){
    return manaBar;
}

public int getLevel(){
    return 1;
}

public boolean isPlayerInsideBoundry(float x, float y){
    Rectangle boundry = Game.getWalkableBounds();

    if(boundry.contains(x,y)){
        return true;
    }

    return false;
}

```

}

**What I've tried:** \- Using a method that checks if the game boundary contains player boundary rectangle. This gave me the same result as what the check statement in my setX did.

# Answer
either shift the right edge of `getWalkableBounds` to account for the geometry of the player (requires a new second function for the `renderableBounds`)

or you shrink the walkable bounds in the setX function

```
Rectangle gameBoundry = Game.getWalkableBounds();
gameBoundry.width-=PLAYER_WIDTH;
if(x >= gameBoundry.getMinX() && x <= gameBoundry.getMaxX()){
    this.x = x;
}

```

and do the same in `isPlayerInsideBoundry`
> 0 votes

---
Tags: java
---


title: Physics like asteroides

text:
# Question
Title: Physics like asteroides
I try to make a ship that has the physic properties like asteroides. I have this for now(All in Java):

**Ship.class**

```
public class Ship
{
    public static final float sMaxHealth            = 0.1F;
    public static final float sMaxMoveVelocity      = 5.0F;
    public static final float sMaxAngleVelocity     = 20.0F;
    public static final float sRadius               = 1.0F;
    public static final float sMoveDeceleration     = 10.0F;
    public static final float sMoveAcceleration     = 2.0F;
    public static final float sAngleDeceleration    = 15.0F;
    public static final float sAngleAcceleration    = 20.0F;

    private float mHealth;
    private float mXVelocity;
    private float mYVelocity;
    private float mAngleVelocity;

    private float mX;
    private float mY;
    private float mAngle;
}

```

(I let the getter and setter away for now)

**Controller code**

```
        // Player input
        if(Gdx.input.isKeyPressed(Keys.UP))
        {
            mPlayer.setXVelocity(mPlayer.getXVelocity() + (float) Math.cos(mPlayer.getAngle()) * Ship.sMoveAcceleration);
            mPlayer.setYVelocity(mPlayer.getYVelocity() + (float) Math.sin(mPlayer.getAngle()) * Ship.sMoveAcceleration);
        }
        if(Gdx.input.isKeyPressed(Keys.LEFT))
        {
            mPlayer.setAngleVelocity(mPlayer.getAngleVelocity() + Ship.sAngleAcceleration * pDeltaTime);
        }
        if(Gdx.input.isKeyPressed(Keys.RIGHT))
        {
            mPlayer.setAngleVelocity(mPlayer.getAngleVelocity() - Ship.sAngleAcceleration * pDeltaTime);
        }

        // X velocity
        if(mPlayer.getXVelocity() < 0)
        {
            if(-mPlayer.getXVelocity() > Ship.sMaxMoveVelocity)
            {
                mPlayer.setXVelocity(-Ship.sMaxMoveVelocity);
            }
            mPlayer.setXVelocity(mPlayer.getXVelocity() + Ship.sMoveDeceleration * pDeltaTime);
            if(mPlayer.getXVelocity() > 0)
            {
                mPlayer.setXVelocity(0);
            }
        }
        else
        if(mPlayer.getXVelocity() > 0)
        {
            if(mPlayer.getXVelocity() > Ship.sMaxMoveVelocity)
            {
                mPlayer.setXVelocity(Ship.sMaxMoveVelocity);
            }
            mPlayer.setXVelocity(mPlayer.getXVelocity() - Ship.sMoveDeceleration * pDeltaTime);
            if(mPlayer.getXVelocity() < 0)
            {
                mPlayer.setXVelocity(0);
            }
        }

        // Y velocity
        if(mPlayer.getYVelocity() < 0)
        {
            if(-mPlayer.getYVelocity() > Ship.sMaxMoveVelocity)
            {
                mPlayer.setYVelocity(-Ship.sMaxMoveVelocity);
            }
            mPlayer.setYVelocity(mPlayer.getYVelocity() + Ship.sMoveDeceleration * pDeltaTime);
            if(mPlayer.getYVelocity() > 0)
            {
                mPlayer.setYVelocity(0);
            }
        }
        else
        if(mPlayer.getYVelocity() > 0)
        {
            if(mPlayer.getYVelocity() > Ship.sMaxMoveVelocity)
            {
                mPlayer.setYVelocity(Ship.sMaxMoveVelocity);
            }
            mPlayer.setYVelocity(mPlayer.getYVelocity() - Ship.sMoveDeceleration * pDeltaTime);
            if(mPlayer.getYVelocity() < 0)
            {
                mPlayer.setYVelocity(0);
            }
        }

        // Angle velocity
        if(mPlayer.getAngleVelocity() < 0)
        {
            if(-mPlayer.getAngleVelocity() > Ship.sMaxAngleVelocity)
            {
                mPlayer.setAngleVelocity(-Ship.sMaxAngleVelocity);
            }
            mPlayer.setAngleVelocity(mPlayer.getAngleVelocity() + Ship.sAngleDeceleration * pDeltaTime);
            if(mPlayer.getAngleVelocity() > 0)
            {
                mPlayer.setAngleVelocity(0);
            }
        }
        else
        if(mPlayer.getAngleVelocity() > 0)
        {
            if(mPlayer.getAngleVelocity() > Ship.sMaxAngleVelocity)
            {
                mPlayer.setAngleVelocity(Ship.sMaxAngleVelocity);
            }
            mPlayer.setAngleVelocity(mPlayer.getAngleVelocity() - Ship.sAngleDeceleration * pDeltaTime);
            if(mPlayer.getAngleVelocity() < 0)
            {
                mPlayer.setAngleVelocity(0);
            }
        }

        mPlayer.setX(mPlayer.getX() + mPlayer.getXVelocity() * pDeltaTime);
        mPlayer.setY(mPlayer.getY() + mPlayer.getYVelocity() * pDeltaTime);
        mPlayer.setAngle(mPlayer.getAngle() + mPlayer.getAngleVelocity() * pDeltaTime);

```

Why the ship does not behave like in asteroides ? What do I wrong?

# Answer
I assume you mean this game.

I suggest that you take a look at the Wikipedia references for the game. One of them tells you that both drag and inertia are involved - I don't see any drag in your code for a start.
> 0 votes

---
Tags: java
---


title: Server side random selection of players

text:
# Question
Title: Server side random selection of players
Assuming I have a simple client-server game, where the server picks random players on a very frequent base, I was wondering what is the best way to select a random player (According to the following constraints):

1. Solution must be high performance and highly scalable
2. Random spread should be relatively even (meaning if I have 3 players and pick 99 times, they will all be picked 33 times more or less)
3. Should only pick players who were active in the past X days (optional, but a big bonus)

The actual DB or data model used to store players isn't an issue here, as we'll select the technology in accordance to our needs.

However, high performance and scalability is (at the moment we have over 60,000 unique daily active players, and we plan on growing even more).

Thanks!

# Answer
Select players from the database who fit your criteria (active in the past X days,) and put them into an array. Then use a good random number generator to generate a number in the range \[0, 1\], multiply that number by the size of your list, round the result, and use it to index into your list of users.
> 2 votes

# Answer
Since putting 60k player in an array just to select one of them sounds pretty dangerous to performance, you'd probably be best of with using your DB's inbuilt features.

If you are using SQL, then this code snippet will help you. You can easily add your third requirement (be active) by adding a WHERE-clause to the query.

Make sure to replace N by the size of your DB-table.

```
SELECT column FROM table
OFFSET RANDOM()*N
LIMIT 1

```
> 0 votes

---
Tags: algorithm, server, random, databases
---


# Question
Title: How many people should be involved in a game startup?
I want to start an indie game company, and I understand that you need a designer, an engineer, and an artist at the very least. I also know that professional game companies like Bethesda http://bgs.bethsoft.com/ have around 40 people.

I want to have a good start, and many of you have been in the industry for a good while.

What is a good number of employees to start with for an independent game company?

Reasons?

# Answer
> 4 votes
You will need as many people as it takes to create and sell your first game.

How many and what kind of people these are depends solely on the game you want to make and how ambitioned you want it to be in regards to gameplay, graphics, sound, writing, world-size etc. Depending on these factors (and many more), the required project team can be anywhere between one and one hundred people.

To get an estimation for how many people you need, you need to do the same thing which needs to be done for any software development project: Create a project plan. Clearly define the scope of your project. Create a detailed list of all the things which need to be done to complete the project. The more detailed the better. "Make graphics" is much too rough. "Make tilesets, player sprites and monster sprites" is better, but still not nearly detailed enough. "Make about 20 different monsters, sized 32x64 px, each with 12 different animations consisting of 1-6 animation phases each" starts getting you somewhere.

Then make an estimate how many man-hours you will need to complete each of these bullet-points. Then double or triple that estimate, because experience tells us that the effort which goes into a software development project is always grossly underestimated, never overestimated. In some cases you might not have a good idea how long something will take, especially when it is something you never did yourself. In that case, do your research and find out.

You should now have a rough idea what human resources you need to create the game. The next thing you should ask yourself is if you can afford these people. Anyone with a minimum level of professionalism will not work for free, and you will need to pay these people even when it turns out your game doesn't sell a single copy. This worst-case scenario is something you always have to plan for. Total project failure is a possible outcome of every software project, even those managed by the most professional project leaders. When you can not afford to lose every single cent you invested in your project, then do not take that risk.

This might be the moment where you realize you are trying to bite more than you can chew and might decide to downscale your project to something you can complete on your own without external help. In that case all you have to lose is the time you invest. Or maybe you do have some savings lying around and are willing to bet that money on your project?

Whatever decision you make, I honestly wish you the best luck.

---
Tags: business
---


# Question
Title: How do I get mouse x / y of the world plane in Unity?
I am trying to make a tiled landscape. The terrain itself is not made from tiles but the world has a grid which I define.

I would like to place boxes/rectangles which snap to this grid, at runtime, but in order for me to do that I must get a projection from the user screen to the real-world coordinates.

I have tried various examples using the Ray class but nothing worked. It compiles and outputs a constant value no matter where I put the mouse. I have tried to add some tiles and try to detect them but no luck. I also tried with one plane as big as my world but still no luck.

I am using C# but even a JS version would be helpful.

This technique involves calculating which tile the mouse is under by the x and y positions. Perhaps detecting which tile itself is being pointed to would be a simpler task, at which point I can just retrieve its i/j properties.

# Answer
Instead of using a collider for your terrain, you can also use a plane to perform a raycast. For example, if your grid is situated on the XZ plane, you can do something like this:

```
static Plane XZPlane = new Plane(Vector3.up, Vector3.zero);

public static Vector3 GetMousePositionOnXZPlane() {
    float distance;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if(XZPlane.Raycast (ray, out distance)) {
        Vector3 hitPoint = ray.GetPoint(distance);
        //Just double check to ensure the y position is exactly zero
        hitPoint.y = 0;
        return hitPoint;
    }
    return Vector3.zero;
}

```

This will return a 3D world position of where the mouse intersects with the XZ plane. You can then round the `x` and `z` values to the nearest integer value to have a snapping effect when placing your objects. Similar to how Bummzack does in his code:

```
position.x = Mathf.Round(position.x / GridSize) * GridSize;
position.z = Mathf.Round(position.z / GridSize) * GridSize;

```

Using the plane method ensures you don't have to change the size or position of your terrain collider when moving around your world.
> 8 votes

# Answer
First of all, you need to attach a collider to your terrain in order to get hits from raycasts. If you're using a `Terrain`, it should already have a `Terrain Collider` attached to it.

In your script you can then do something like this:

```
// create a ray from your mouse-position
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(r, out hit)){
    // if the ray hit a collider, we'll get the world-coordinate here.
    Vector3 worldPos = hit.point;

    // round coordinates to grid-size (GridSize could be a constant or a
    // public class member that you can change in the Inspector).
    worldPos.x = Mathf.Round(worldPos.x / GridSize) * GridSize;
    worldPos.z = Mathf.Round(worldPos.z / GridSize) * GridSize;
    // you can do the same for the y-coordinate, if you need grid
    // snapping in the y-axis.

    // position your object at the calculated position:
    MyObject.transform.position = worldPos;
}

```

From your question I assumed that your grid only applies to the X & Z axes. Of course you could also apply it to the Y axis or leave the Y coordinate untouched (which will position the object at the Y position of the ray/terrain intersection). If you have a terrain with elevation, this might not lead to the desired results and you'll have to cast another ray downwards at the new position (eg. the one that lies on your X/Z grid) to get the exact Y-coordinate.
> 3 votes

---
Tags: unity, picking, unityscript
---


# Question
Title: Libgdx Box2d createfixture crashes vm intermittently
I have a hard to debug problem. I have a Box2D game which creates a wheeled vehicle. I want the vehicle body to reflect when it goes from moving left to moving right. to do this i set a flag in a changelistener on a button and then in update method i destroy and recreate the body facing the other way. it works fine most of the time but if i flip the vehicle several times quickly JVM crashes. no errors nothing in log.

i added system.out.prints and the errors occur in the routine that instantiates the new body and before anything gets deleted/removed so i don't think the UI is trying to access null pointers. and if it was it should throw an error. M the crash seems to be at createFixture statements. but the work most of the first time. I tried debugging but the error doesn't happen much when the flips are slow. in any case createFixture drops fairly quickly into jni.

Is this a Box2D bug? Is GC the issue? From Mission Control I see the GC is collecting on a period of ooh maybe 5s and flipping slower than that mostly works.

how do i debug this?

i am win7 64bit with 64bit at and jdk7 64bit. libgdx-0.9.9 and sometimes libgdx-nightly-20140215.

# Answer
> 1 votes
I had the same problem and I solved mine, but this might not be your problem.

What I did was, at one point to reset/cleanup:

```
world.dispose();
world = null;
world = new World(...);

```

Apparently this is no good and leads to crashing (sometimes?)

So instead I just used world.destroyBody() and whatnot, and that solved it.

---
Tags: java, libgdx, box2d
---