# Question
Title: Can't find out why aren't those collisions framerate independent
I'm making a 2D Platform game and I'm having trouble with my collision detection. It doesn't seems to be framerate independent even though I used deltatime there.

The problem is that at 60fps, a collision is sometimes detected too early whereas at 500fps there's no problem (so it really seems like this isn't framerate-independent but I don't know why).

Here's a video of the game running at 60fps https://www.youtube.com/watch?v=P0hRJbw\_gcw

And here's the code which is moving my character (I inspired myself about 2D Collision detection from the youtuber dermetfan):

```
/// Makes the entity jump
void Entity::jump()
{
    m_onGround = false;
    setVelocity(sf::Vector2f(getVelocity().x, -500));
}

/// What to do at each frame
void Entity::update(sf::Time dt)
{
    if (getVelocity().y > 800)
    {
        setVelocity(sf::Vector2f(getVelocity().x, 800));
    }
    else
    {
        setVelocity(sf::Vector2f(getVelocity().x, getVelocity().y - m_map->getGravity()*dt.asSeconds()));
    }

    checkCollisions(dt);
}

/// Collision functions
void Entity::checkCollisions(sf::Time dt)
{
    float oldX = getPosition().x;
    float oldY = getPosition().y;

    bool collX = false;
    bool collY = false;

    setPosition(getPosition().x + getVelocity().x*dt.asSeconds(), getPosition().y); // Setting the position on x

    m_collisionIncrement = (getSize().x < getMap().TILE_SIZE) ? getSize().x / 2 : getMap().TILE_SIZE / 2;

    if (getVelocity().x < 0)
        collX = collidesLeft(); // Using collision tests
    else if (getVelocity().x > 0)
        collX = collidesRight();

    if (collX){ // Testing if there was a collision
        setPosition(oldX, getPosition().y); // Correct position
        setVelocity(0, getVelocity().y*dt.asSeconds());
    }

    setPosition(getPosition().x, getPosition().y + getVelocity().y* dt.asSeconds()); // Setting the position on y

    m_collisionIncrement = (getSize().y < getMap().TILE_SIZE) ? getSize().y / 2 : getMap().TILE_SIZE / 2;

    if (getVelocity().y > 0)
    {
        collY = collidesBottom();
        m_onGround = collY;
    }
    else if (getVelocity().y < 0)
    {
        collY = collidesTop();
    }

    if (collY){ // Testing if there was a collision
        setPosition(getPosition().x, oldY);
        setVelocity(getVelocity().x*dt.asSeconds(), 0);
    }
}

bool Entity::collidesRight()
{
    for (float step = 0; step <= getSize().y; step += m_collisionIncrement)
    {
        if (getMap().isCollideable(getPosition().x + getSize().x, getPosition().y + step))
            return true;
    }
    return false;
}
bool Entity::collidesLeft()
{
    for (float step = 0; step <= getSize().y; step += m_collisionIncrement)
    {
        if (getMap().isCollideable(getPosition().x, getPosition().y + step))
            return true;
    }
    return false;
}
bool Entity::collidesTop()
{
    for (float step = 0; step < getSize().x; step += m_collisionIncrement)
    {
        if (getMap().isCollideable(getPosition().x + step, getPosition().y))
            return true;
    }

    return false;
}
bool Entity::collidesBottom()
{
    for (float step = 0; step < getSize().x; step += m_collisionIncrement)
    {
        if (getMap().isCollideable(getPosition().x + step, getPosition().y + getSize().y))
            return true;
    }
    return false;
}

```

# Answer
Making collision detection frame rate independent is basically impossible. While you can reasonably implement frame rate independent rigid body motion and many other simulations by multiplying by dt (delta time), actual collision detection is "impossible" to do frame rate independent.

To illustrate the issue let us assume you have a small cube moving at a high velocity and there is a thin wall in the way. Physics simulation is generally implemented by checking if there are collisions, apply any forces/impulses if it was the case and then advance the simulation by a fixed or dynamic amount of time. The problem comes if the speeding cube is before the wall in one frame and completely after the wall in the next. It did not collide (= intersect) with the wall in the first and it does not collide next frame, for all purposes of the simulation it never collided with the wall.

To remedy this problem there are two solutions. The first is to take into account the motion since the previous frame and take that into account during collision detection. The problem with this is that it makes an already quite computationally expensive operation even more expensive. The second solution is to ensure that your tick rate is sufficiently small to represent the velocities in play. This can either be solved my reducing the tick rate or limiting the maximum velocities of the simulation.

Generally speaking the optimal solution to numeric simulations (rigid body simulation is one) is to use a fixed dt and simply accumulate the ticks in a frame rate (graphic) independent fashion. For example you decide to let your physic simulation tick at 10ms. But you (must) do the simulation interleaved with the render loop. Say this frame 54ms where passed since the last simulation, then you call the simulation 5 times with 10ms and add 4ms to an accumulator. The next frame 68ms where passed, since you have 4ms on the accumulator you run the simulation 7 times and add set the accumulator to 2ms (68+4=72). This also works well when the frame rate is below the tick rate, if 7ms passed since the last frame add 7ms to the accumulator, if it is below 10ms you skip the simulation for this frame.

A constant tick rate for the simulation not only ensures that the collision detection is more stable, it also makes the simulation more deterministic. This means that two machines running the same simulations will have the same result.
> 1 votes

# Answer
If you keep track of the position at last frame you can also create a line from last position to current position and do line to rectangle collision detection to see if you went though the terrain.
> 0 votes

---
Tags: collision-detection, sfml, frame-rate
---


# Question
Title: Libgdx, tiled map - how to reload layer?
In the simple platform game I'm making, when player collects coin, its cell is set to `null`. Is it possible to recover all cells from layer "coins" after player dies? I have tried multiple things but none of them worked :/

Here is part of code responsible for collecting coins:

```
for (Rectangle coins : coins) {
        TiledMapTileLayer layer_coins = (TiledMapTileLayer)map.getLayers().get("coins");
        if(dotRect.overlaps(coins)){
            layer_coins.setCell((int)coins.x, (int)coins.y, null);
            coinsN++;
            Sounds.playCoin();
        }
    }

```

But when player dies and re-spawns, there are no coins if he collected them before. I tried reloading the map - it works fine, but loading after every death is unacceptable - it takes a lot of time.

EDIT: Now I have another problem, with loading TiledMapTile to put into cell...

```
TiledMapTile coinTile;

public void show() {
    TextureRegion mapTexture1Region = new TextureRegion(mapTexture1, 32, 0, 16, 16);
    coinTile.setTextureRegion(mapTexture1Region);
}

```

It gives me NullPointerException, and I have no idea why :/

# Answer
You could have an array of coordinates of collected coins, and then iterate over that and restore them when the level should be restarted.

In general, for this problem you will want to keep the information around that you will still need later. You can do this either by remembering specific things explicitly or by cloning the original data.
> 2 votes

---
Tags: libgdx, maps, tiled, layers
---


# Question
Title: Pathfinding in a 2D "sidescrolling" strategy game
I've been thinking up a real-time strategy game that plays on a platformer type of map. The collidable portion of these maps will be made up of square tiles. I've done A\* pathfinding in top down tile based games before, but I'm unsure how to lay out my tile map in such a way that allows for easy pathfinding. I've thought up some examples, but I'm not sure if it's the right way to go about it, so I thought I'd throw it out here and see if someone who knows what they're doing can give me some tips.

The first solution I thought of was to use a 2D array storing all of the tiles and empty space, similar to what I would most definitely do in a top down tile based strategy game. The 2D grid would be invisible in the background but really store whether each grid section is empty, or has a tile on it. like this:

In this example I'm unsure as to how I would pathfind up hills, or in that specific example, determine that a wall is too high to cross. Lets say that dude can jump over 1 tile high blocks, but 2 tiles is too much. How would I effectively determine that through a pathfinding algorithm?

The other example I was thinking of was to place pathfinding nodes on top of traversible terrain, like this:

Each node might be able to give directions or commands on how to get to the next (Like the need to jump to cross a gap, or it's faster to go under rather than over, etc). Now I would want to do this logically through code, and not manually place them at design time.

This might be a better solution, but something I'm thinking of in this game is to have destructable terrain. Say an explosion happens and leaves a big hole like this:

Suddenly those nodes I placed earlier won't work. I'd need to remake them on the fly. In this case the 2D grid sounds like the better option since I can just flip the value of that tile from full to empty.

So hopefully those 2 examples made sense, and I'd like some opinions on which might be the best option, or even if there's some other solution I didn't think about I would be glad to hear it! I'm using Unity if that helps.

I just want to get this design choice out of the way early, as it would be a pain to have to tear it apart later.

Thanks!

# Answer
> 3 votes
A\* operates fundamentally on a graph, **not a grid**. When you create a grid for A\* to search, what you've actually done is created something called a "lattice graph." The connections between nodes in the lattice can be anything. They don't have to just be straight lines between neighboring grid cells. In your case, you can combine the best of both worlds just by connecting up neighbors in a different way in the lattice graph. By changing your definition of "neighbor", you can alter the kinds of paths that can be produced by A\*.

```
// Expands the valid neighbors of a cell within a grid.
List<Cell> GetNeighbors(Cell node, Grid grid)
{
    List<Cell> neighbors= new List<Cell>();

    // Get all the cells in the immediate neighborhood
    Cell top      = grid.GetCell(node.x,     node.y + 1);
    Cell left     = grid.GetCell(node.x - 1, node.y);
    Cell bottom   = grid.GetCell(node.x,     node.y - 1);
    Cell right    = grid.GetCell(node.x + 1, node.y);
    Cell topright = grid.GetCell(node.x + 1, node.y + 1);
    Cell topleft  = grid.GetCell(node.x - 1, node.y + 1);

    bool isOnGround = bottom.IsOccupied;
    bool isHeadCovered = top.IsOccupied;

    // If we're not standing on the ground, we can only fall.
    if (!isOnGround)
    {
        neighbors.add(bottom);
        return neighbors;
    }

    //Otherwise, we can try walking left or right
    if (!left.IsOccupied) neighbors.add(left);
    if (!right.IsOccupied) neighbors.add(right);

    // If our head isn't covered, we can try jumping up one,
    // or up to the left and right.
    if (!isHeadCovered)
    {
        // Only jump up if the cell we're jumping on top of is occupied.
        if (!topleft.IsOccupied && left.IsOccupied) neighbors.add(topleft);
        if (!topright.IsOccupied&& right.IsOccupied) neighbors.add(topright);
    }

    return neighbors;
}

```

Then, in A\*, when you expand nodes, expand only to the valid neighbors. You might also want to expand your definition of "Node" to include the action it took to get to that node (for instance, jumping, falling, or walking), so that the character can take the proper action while following the path. You can also add additional pathfinding constraints like climbing ladders or destroying things.

---
Tags: unity, algorithm, path-finding, strategy, realtime
---


# Question
Title: Should a game clean up after itself when exiting?
Should a game/engine clean up after itself(close windows, shut down renderers, close files, free memory) when its closed?

The OS should do that anyway, and usually in a faster way.

I guess most developers don't really care as they need proper cleanup for everything anyways(With dynamic asset-loading, and changing maps, etc.), but won't ensure that everything gets cleaned perfectly.

But is there any positive to cleaning up vs not cleaning up or the reverse?

I am using C++.

What about game consoles? Do they all clean up after themselves?

# Answer
> 9 votes
Yes, a game/engine should clean up after itself when it's closed. There are good reasons for that:

* Show to your team that you know what's going on in your game
* Know when your managers are shut down
* Make sure your files and handles are closed and your data is saved
* Help prevent crashes on exit because you have a better idea to what's going on
* Help find memory leaks: if you clean everything yourself, you should not have any memory leaks, so the next time you use a tool to detect them, it should give you 0 leaks. You'd have a harder time achieving this if you don't clean on shutdown.

And it smells fresher when stuff is clean!

# Answer
> 0 votes
if you have used `malloc()` or similar memory allocation functions then you must use `free()` to destroy the allocated memory when your done, and similar when you use the **new** operator to create an instance of something then you must use `delete()` to destroy it when done, otherwise those resources and memory may still exists or be locked up in the background, so its good practice to de-allocate memory yourself to be safe.

---
Tags: c++, memory
---


# Question
Title: Since D3DX utility library is deprecated, what can I do about this legacy code?
D3DX Structures utility library is deprecated for Windows 8 and its not supported for Windows Store apps. So my question is, Does anyone know what to replace this legacy code with..

```
std::vector<ID3D11Texture2D*> srcTexture(size);
for(UINT i = 0; i < size; ++i)
{
    D3DX11_IMAGE_LOAD_INFO iload;

    iload.Width  = width;
    iload.Height = height;
    iload.Depth  = D3DX11_FROM_FILE;
    iload.FirstMipLevel = 0;
    iload.MipLevels = D3DX11_FROM_FILE;
    iload.Usage = D3D11_USAGE_STAGING;
    iload.Format = format;
    iload.BindFlags = 0;
    iload.CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
    iload.MiscFlags = 0;
    iload.Filter = filter;
    iload.MipFilter = mipFilter;
    iload.pSrcInfo  = 0;

    HR(D3DX11CreateTextureFromFile(d3ddevice, filename[i].c_str(),
        &iload, 0, (ID3D11Resource**)&srcTexture[i], 0));
}

```

I have been using directXTK to try an replace them but its a difficult process, both D3DX11CreateTextureFromFile and D3DX11\_IMAGE\_LOAD\_INFO still need replaced and D3DX11\_FROM\_FILE is also a depreciated parameter, is there an alternative or effective solution available?

thx in advance

# Answer
> 2 votes
This particular code is loading images (maybe DDS files or maybe general bitmap files) into a CPU staging resource doing a format conversion and resize. Presumably you are going to do something else with the `srcTexture` array that actually creates the resource you are going to render with. This is a lot of runtime processing, so the *best* option is to do that offline and just create a .DDS file with whatever your final resource should be. Then you have a simple case of using the DDSTextureLoader functions in DirectX Tool Kit to do the load with complex file parsing, format conversion, or resizing.

If you don't control your resource files (i.e. they come from the user or the web), or you are doing some kind of application where you really are doing a lot of processing a part of the application itself, then you should use DirectXTex instead. See the source to `texconv` for full details. You'll end up calling:

* `LoadFromWICFile` to a `ScratchImage`
* If the size is changing, call `Resize`
* If the format is changing, call `Convert`
* If you need mipmaps, call `GenerateMipMaps` or `GenerateMipMaps3D`
* If you are really needing a GPU STAGING resource, call `CreateTextureEx` so you can provide the usage, bindFlags, cpuAccessFlags, and miscFlags.

See this blog post as for why there are two different libraries here.

---
Tags: c++, directx11
---


# Question
Title: Why doesn't OnCollisionStay execute continuously?
I'm currently trying to build a simple demo where the player can jump. This is the script I have setup so far.

```
using UnityEngine;
using System.Collections;

public class PlayerJump : MonoBehaviour
{
    public Vector3 jumpForce;

    void OnCollisionStay (Collision other)
    {
        print("OnCollisionStay");
        if (Input.GetKey (KeyCode.Space) && other.gameObject.tag == "Block")
        {
            rigidbody.velocity += jumpForce;
        }
    }
}

```

Whenever I check the console, the message `"OnCollisionStay"` is only printed 21 times. Just for more details the GameObject this script is attached to contains a rigidbody that uses gravity, has the x, y, and z rotation axes frozen, and the z position axis forzen as well. The gameObject I'm trying to collide with has a simple box collider attached to a cube with a scale of `(5, 1, 5)`. What am I doing wrong? I am under the impression that `OnCollisionStay` continuously executes until the player is no longer colliding with anything, then starts executing again on collision?

# Answer
This sounds like the object is at rest and the Rigidbody has been put to sleep.

You can modify `Rigidbody.sleepThreshold` to change this behaviour for a single instance.

Alternatively you can change the threshold project wide via the Physics Manager. Try setting "Sleep Threshold"/"Sleep Velocity" to zero.
> 2 votes

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


# Question
Title: How should entities in a game reference each other?
I've been reading a lot about design patterns, but in using these patterns there's one question that I keep coming back to. How should my entities access information about each other?

Let's say I'm using a simple pattern where each object updates and draws itself:

```
class Monster extends GameEntity {
    public void update(double delta) {}
    public void draw(Graphics g) {}
}

```

I'm writing my update loop, but I realize that for Monster requires knowledge about where the player is, where cities on the main map are, or some other random piece of data.

How does Monster get at this? Do I initialize it with a reference to every possible thing it might need?

```
class Monster extends GameEntity {
    public Monster(Player player, City[] cityList) {
        this.player = player;
        this.cityList = cityList;
    }
}

```

That looks pretty messy. Or do I have a main Manager of sorts, which has access to everything, and pass that to everything?

```
class Monster extends GameEntity {
    public Monster(GiantGlobalManager manager) {
        this.manager = manager;
    }

    public void update(double delta) {
        cities = this.manager.getCities();
    }
}

```

Or perhaps have the manager as singleton? We could also break these managers into their areas of concern.

```
class Monster extends GameEntity {
    public void update(double delta) {
        cities = CityManager.getInstance().getCities();
        player = PlayerManager.getInstance().getPlayer();

        guiManager.getInstance().createMenu();
    }
}

```

But this still doesn't feel quite right. Now I'm having to maintain all these managers, and it seems wrong for my objects to be making all these static calls. Second, many of these objects should not have access to everything provided by these classes. Letting everything access everything feels like a cop-out to me.

Whatever patterns I'm using - whether I'm breaking entities into components, or just moving my drawing and update loops to separate objects - I still need some way for them to communicate. What is a good way to go about this? What am I missing here?

Should this all be done through events? But getting a list of cities is not really an event, it's just data the monster needs.

# Answer
As you've noticed, there are pros and cons to each architecture scheme. Each pattern has its own implications for how objects will interact, and when.

First, I'd recommend a quick refresher on SOLID design.

Now, what we strive to accomplish with good architecture is enough abstraction that we aren't hampered by the system when we want to add a feature. If we can accomplish that with a couple of singletons or global methods in a way that *scales to future development*, great! It might even end up faster.

Now, the object oriented approach typically has one or more factories that produce either generic entities you add components to, or specific entities in a non ECS design. These factories are usually contained close to the core gameplay class. As an example of the non-ECS version:

```
class Monster extends GameEntity {
    // Called by factory
    public Monster(EntityService service) {
        // store a private reference to the service
    }
    public GameEntity Find( /* parameters depend on game's needs */ ) {
        // call methods on service to locate entities given these conditions
    }
    public void Destroy() {
        myService.Remove(this);
    }

}

class MonsterFactory extends GameEntityFactory {
    private EntityService myService;
    public MonsterFactory(EntityService service) { /* ... */ }
    public GameEntity Spawn()
    {
        GameEntity entity = new Monster(myService);
        myService.Add(entity);
        return entity;
    }
}

class Physics {
    private EntityService myService;
    public Physics(EntityService service) {
        /* retain service in order to provide updates to entities */
    }
    public void update(double delta) {
        // make changes to each applicable entity in
        // "myService," which the entity will refine
        // in its own update method
    }
}

```

The common thread here is that each object is constructed with a reference to a *service* that provides some core functionality where the specific behavior is abstracted according to how the object will always behave. Need to create a monster? Summon the monster-making-factory from the entity service. Need to find another entity? It's in the entity service. Need to send messages to all entities of a certain type (such as physical entities)? Just filter them out of the entity service. This way you can avoid hanging on to references to "dead" entities.

This is just one example, of course. In practice, your game's needs will dictate how this has to come together.
> 7 votes

# Answer
A slight variant to jzx's implementation would be to use an update method similar to how you did your draw. It's not uncommon in architectural design to have some context object that often holds a plethora of state information.

```
 public interface GameEntity {
   void update(GameContext ctx);
   void draw(RenderContext ctx);
 }

```

Therefore, inside a particular `GameEntity` implementation class you might see your update method written as such:

```
 public void update(GameContext ctx) {
   GameObjectManager goManager = ctx.getGameObjectManager();
   if(!hasTarget()) {
     List<GameEntity> entities = goManager.getVisibleEntitiesWithinRadius(position, 30);
     if(!entities.isEmpty()) {
       setTarget(CollectionUtils.selectRandomFromList(entities));
     }
   }
   // do other stuffs
   SomeGameSystem sgSystem = ctx.getSomeGameSystem();
   sgSystem.process(this, ctx);
 }

```

You could consider inverting this approach where a system acts as both a factory and the place where your update logic resides. These systems are updated in a deterministic order and perform small sets of operations on a large bucket of entities based on criteria. This often yields faster and more cache friendly operations.

Essentially that update logic above could be pushed into a series of systems like this

```
 public AISystem implements System {

   public AISystem(SpacialQuerySystem spacialQuerySystem) {

   }

   public AIComponent createComponent(GameEntity entity) {
     AIComponent component = new AIComponent();
     component.setOwner(entity);
     components.put(entity, component);
     return component;
   }

   public AIComponent getComponent(GameEntity entity) {
     return components.get(entity);
   }

   @Override
   public void update(double deltaTime) {
     for(Entry<GameEntity, AIComponent> entry : components.entrySet()) {
       /* do whatever with the entity and use the injected systems */
     }
   }

 }

```

In the end, this approach becomes far easier to maintain long-term as you can often build foundation systems that you reuse in more complex systems that ultimately implement some game need. Additionally, the use of constructor injection explicitly identifies dependencies in your architecture without having to sift through code to determine what needs what.

All that is left is to have some map loader or such that understands how to read your level data and call the various systems to construct your entities. If you use archetypes and archetype factories, perhaps that can be abstracted into those factories that ultimately interact with these said systems.
> 3 votes

---
Tags: architecture, design-patterns, oop
---


# Question
Title: How to implement server side auto attack?
I'm writing a basic MMORPG and im trying to implement auto attack.

At client side I send an AutoAttackMessage to the server.

Should I send this message every X ms to the server, or juste one time and then server handle this himself ?

How to handle delay between 2 auto attack at server side ? (timer, special thread)...

# Answer
I would say that a client expresses intent to the server to do the following

* Start attacking
* Stop attacking
* Execute a special attack

When a player enters combat on the server side, a simulation is started. The simulation examines the player's weapons and their swing timers and begins calculating when white-attacks (aka auto-attacks) occur to the target. When special attacks are requested, the simulation will carry those out if applicable.

As to how to delay on the server side, it can be as simply as once your first auto-attack happens and your weapon speed is 1.6 seconds, then the simulation will set the swing timer to 1.6 and for each update of the simulation, it will decrease the time that past since the last update. Once the swing timer reaches 0, an auto attack occurs if applicable and the variable is reset back to the weapon swing time and the process repeats.

From this point, the server performs the damage calculations and transmits that information to the client. All the client does is renders the information and nothing more. The server sends that entity XYZ took N damage. The client decrements the health of entity XYZ by N, perhaps adds some scrollable combat text to reflect N damage, adds an entry to the combat logs and proceeds.
> 3 votes

---
Tags: mmo, client-server
---


# Question
Title: Cocos2dx - Touch not recognized on Android
I'm having trouble with a touch listener not picking up touch events on android, but doing fine in windows (mouse input). I've got a Node listening for touches (not a Layer), but from what I've been seeing around it seems having it on a Layer isn't a requirement anymore?

**Setup**

```
void DodgePlayerController::setupPlayerInput()
{
    CCLOG("DodgePlayerController::setupPlayerInput()");
    if (myPawn)
    {
        Pellet* myPellet = dynamic_cast<Pellet*>(myPawn);
        if (myPellet)
        {
            CCLOG("DodgePlayerController::setupPlayerInput() !!2!!");
            //setup the player input and events (should build some sort of player controller)
            auto listener = EventListenerTouchAllAtOnce::create();
            listener->onTouchesBegan = CC_CALLBACK_2(Pellet::setTargetPosition, myPellet);
            listener->onTouchesMoved = CC_CALLBACK_2(Pellet::setTargetPosition, myPellet);
            listener->onTouchesEnded = CC_CALLBACK_2(Pellet::clearTargetPosition, myPellet);
            listener->onTouchesCancelled = CC_CALLBACK_2(Pellet::clearTargetPosition, myPellet);

            auto dispatcher = getEventDispatcher();
            dispatcher->addEventListenerWithSceneGraphPriority(listener, this);
        }
    }
}

```

When logging on Android, I'm getting through both CCLOG messages correctly (I have a 'disablePlayerInput()' which isn't being called, so the listener shouldn't be removed). This all works fine in the windows application, but when I load it in Android the touches aren't picked up (Pellet::setTargetPosition also has a log message which doesn't get thrown in android).

Anyone know what I might be missing?

# Answer
> -1 votes
Try to add *setSwallowTouches (true);* after creating the listener.

---
Tags: android, cocos2d-x, touch
---


# Question
Title: Java Libgdx: How do you add cells to a TiledMap?
I'm trying to make a Side-Scrolling game that will allow you to place/remove tiles. I'm using the TileMap Editor to render the custom Tilemap but is there any way to add tiles? I have it where I can remove the tiles with .setTile(null) but is there anyway to get the properties from a tile in the TileMap Editor so that it can get the Texture/Tile to use so it can place the tile?!

# Answer
You can create a `Cell` and fill that with a tile from the `TileMapTileSet`, then set that cell at **(x, y)** coordinates in a particular `Layer`.

For example, the following code sets the tile at **(32, 64)** in a layer to tile **42** from tile set *tileset\_name*;

```
TiledMapTileLayer layer = (TiledMapTileLayer)map.getLayers().get("some_layer_name");
Cell cell = new Cell();
TiledMapTileSet tileSet = map.getTileSets().getTileSet("tileset_name");
cell.setTile(tileSet.getTile(42)); /* or some other id, identifying the tile */
layer.setCell(32, 64, cell); // 32 and 64 being x and y coordinates

```

In the above code `map` is a `TiledMap`.
> 1 votes

---
Tags: java, 2d, libgdx, tilemap
---


title: Object-oriented Ability System?

text:
# Question
Title: Object-oriented Ability System?
For my RTS game's ability system, I need an efficient ability system where each ability is its own class that implements certain functions from an inherited abstract base class, Ability. Every ability is identified by a byte ID (which gets sent over the network and interpreted by other players). I want to be able to call an ability's overrided Execute() Method with its ID. Currently, I've been thinking of storing all the abilities in dictionaries with their IDs as their keys but I'm having trouble storing these derived classes, abilities, in the dictionary.

I've also heard of reflection but I'm a bit hesitant because I've heard it's a quite expensive operation. Would it be recommended to use up to 60 reflection processes in one frame or will this cause performance issues?

Note: I'm using **C#** and Unity3D.

# Answer
First of all, I would consider making an ability a component, so that it can be attached to any GameObject:

```
abstract class Ability : Component {
    public abstract byte Id { get; }

    public abstract Execute();
}

```

By making the byte id a property, you can easily override the property in each class and give it a unique value, without having to worry about keeping a list:

```
class MyConcreteAbility : Ability {
    public override byte Id {
        get { return 8; } // Byte value of your choosing
    }

    public override void Execute() {
        // Your code here
    }
}

```

(Just make sure not to use the same value twice.)

Additionally, I would add an overloaded version of the method `Execute` to the abstract `Ability` class, to serve as a message handler:

```
public void Execute(byte id) {
    if(Id == id) {
        Execute();
    }
}

```

The ability's `Execute` method can then easily be invoked on all objects it is attached to by calling:

```
BroadcastMessage("Execute", 8)

```

Or on a specific object and all its children by calling:

```
gameObject.SendMessage("Execute", 8)

```

Of course, you can also simply call it directly.
> 3 votes

# Answer
I don't really get it, you are using polymorphism and then you don't?

So far I understand it as the following, you have a base class `Ability` and derived classes that actually implement the ability. So something like:

```
abstract class Ability
{
    abstract public void Execute();
}

class CastMagicMissile : Ability
{
    override public void Execute()
    {
        // some logic to case magic missile
    }
}

```

Why do you want to pass the id of the ability to `Execute`? The ability already knows what type it is. The only thing that remains to actually do is find a mapping from ID to ability, but this can either be solved by a dictionary or a switch statement. I can think of two situations where this may be needed, construction and invocation via the network.

With construction, I would use a factory function, like so:

```
#define MAGIC_MISSILE_ABILITY 1337

abstract class Ability
{
    static public Ability Create(byte id)
    {
        switch (id)
        {
            case MAGIC_MISSILE_ABILITY:
                return new CastMagicMissile();
            default:
                // throw some appropriate error
        }
    }

    //...
}

```

You may want to have a more flexible factory facility, but you get the idea.

With the network invocation issue, I would put an id on each ability, with something like a `GetType` method and the loop that in the invocation. Something along the lines of:

```
class Unit
{
    private List<Ability> abilities;

    public void ExecuteAbility(byte id)
    {
        foreach (Ability ability in abilities)
        {
            if (id == ability.GetType())
            {
                ability.Execute();
                return;
            }
        }
        // throw invalid ability error or ignore
    }
}

```

Note: If you share the ability instances among the units, you may need to pass the reference to the `Execute` method, but that is about it.
> 3 votes

# Answer
You have separate classes for each Ability, although the type of each ability is already defined by ByteID. As such, an "ability" is really just a link between each ByteID and a unique callback. You are unnecessarily defining the callbacks via inheritance.

A static Execute() can "index" which execute() to use with only ByteID.

In this way, all ability *instances* are identically-sized and -typed and will fit in a strongly-typed dictionary.

If all of your callbacks have the same signature, your entire ability system could be replaced with:

```
Dictionary<byte, delegate> Abilities;

Abilities[ByteIDTypes.Something].invoke();

```

In practice, you will need to modify the signature:

```
static Execute(byte whichAbility, byte applyToWhichObjectID)

void ExecuteAbilityOnMe(byte byteID) //Within base-classes supporting execution
{
    if (byteID == 1) return; //1 is not valid for this class
    Abilities[byteID].invoke(byteID, myObjectID); //Do as instructed
    if (byteID == 1) Abilities[1].invoke(1, myObjectID); //Only allow Ability1
    switch (byteID)
    {
        case 1: //Allow Ability1
        case 2: //And Ability2
          Abilities[byteID].invoke(byteID, myObjectID);
          break;
        case default: //But no others
          break;
    }
}

```

and/or ("my" refers to the enemy being clicked):

```
void OnClick(bool leftButton) //Within base-classes supporting execution
{
    if (leftButton) Abilities[ByteIDTypes.Attack].invoke(ByteIDTypes.Attack, myObjectID);
}

```
> 1 votes

---
Tags: c#, rts, code-reflection
---


# Question
Title: How to rotate a gameobject to the specific angle
I have tree model that is being rotating .After certain angle it should stop rotating.I have done a sample code.But the tree is not stopping.

```
void Update () {

        //transform.Rotate (0f,0,0.5f*Time.deltaTime);
        //transform.Rotate (Vector3.forward,Time.deltaTime*5);
    transform.Rotate (0f,0f,time);
    Debug.Log(time);
    time+=0.5f;
   if(time==5.5f)
    {
        transform.eulerAngles=Vector3.zero;
    }

```

}

From the above code I need to stop the rotation when the z axis value is 5.5f.How can I do this . Please help me.

# Answer
Instead of doing: `if (time == 5.5f)`, you need to do: `if (time >= 5.5f)`.

The rotation is stopping for a short amount of time (One update), but then the time variable is increased the next update. Its not equal to 5.5 anymore, so the rotation continues.
> 1 votes

# Answer
It's pretty easy, once it reaches 5.5f indeed the rotation vector should be zero, but this is `Update()` we're talking about. If we take what you have written outside of the if statement :

```
transform.Rotate (0f,0f,time);
Debug.Log(time);
time+=0.5f;

```

On every frame, your object will rotate by 0.5 eulerAngle, then 1, then 1.5, infinitely. To fix this you can just make a bigger if statement like this :

```
time+=0.5f;
 if(time!=5.5f) {
transform.Rotate (0f,0f,time);
 }
 else
{
    transform.eulerAngles=Vector3.zero;
}

```

This should logically work.
> 0 votes

# Answer
```
void Update () {
    //if you are past the amount of degrees, then you don't need to rotate more.
    if (this.transform.rotation.eulerAngles.z > /*amount of degrees*/ 5.5f) return;

    //rotate more
    this.transform.Rotate (0, 0, 0.1f);
}

```

Or better, I would make a quaternion of the starting angle and the end angle ( using: http://docs.unity3d.com/ScriptReference/Quaternion.Euler.html ), then I would lerp ( using: http://docs.unity3d.com/ScriptReference/Quaternion.Lerp.html ) between the two values.

Hope that helps!
> 0 votes

---
Tags: c#, unity, rotation
---


# Question
Title: How to find damage per second using Average Damage, Accuracy and Fire Rate Per Second?
I was wondering if anyone could help me establish a DPS equation using the variables 'Average Damage', 'Accuracy (%)', and 'Fire Rate Per Second'.

Here is my table:

Note: These numbers are examples only!

# Answer
> 4 votes
Why not this way? Much easier?

damagePerSecond = averageDamage * fireRatePerSecond * accuracy

Example:

damagePerSecond = 140 * 10 * 0.09

# Answer
> 0 votes
DPS = (total / rate) * accuracy;

so for shotgun:

```
damagePerShot = 140;
totalPerSec = damagePerShot * 10;
dps = (totalPerSec / 100) * 9;

```

so I figure average dps of 126 for a shotgun. Sound Good?

---
Tags: game-design, mathematics, statistics
---


title: Pixelated Text in Game Maker

text:
# Question
Title: Pixelated Text in Game Maker
Is there a way to make the text look smoother and less pixelated? It bothers me.

# Answer
> 2 votes
If you used a small size of the view then you can set a different resolution for GUI and draw text from `Draw GUI` event. Create a font with needed size and just draw it.

For example, if your window is 1024\*768 (but small view - for example, 320\*240)

```
display_set_gui_size(1024, 768);

```

---
Tags: game-maker
---


# Question
Title: How to force a translation to go through an exact point?
I have a camera object with a script that will whether translate it with a set speed, or stop it. I also have 7 "checkpoints", where there are 7 different quads, who will stop the camera whenever the camera reaches them.

The problem here is that in my code :

```
void Update() {

if (scoreholder.CheckScore()<scoretimer) {
//if the current score is less than set X score

        if (killcam.transform.position.y == quadholder.y) {
//and if the camera's position equals the position of the generic quad *PROBLEM HERE*

            killcam.GetComponent<cameraUp> ().SetCam (true); //stop the cam

            while (scoreholder.CheckScore () < scoretimer) { // do stuff

                offset = mr.material.mainTextureOffset;
                offset.y += offsetSpeed * 0.1f;
                mr.material.mainTextureOffset = offset;

                break;
            }
        }

    }

else { //once the score is not less than the desired X score, move the cam
        killcam.GetComponent<cameraUp> ().SetCam (false);
    }

}

```

So my problem here is that this line of code `if (killcam.transform.position.y == quadholder.y)` never happens, the translation skips some values, and the camera doesn't hit the exact quad spot. I tried to use `>` instead of `==`, but I ran into another problem, is that after the 3rd quad, since my camera speed increases in time, the code apparently doesn't get processed fast enough, and my camera goes beyond the 4th,5th,6th, and 7th quad without stopping.

I have already tried `Vector3.Lerp`, and it gives me almost the same result, if I lerp between the beginning and the end of the track, I have to do it with an extremely small fraction, and I can't have my camera move at that speed.

# Answer
> 2 votes
`Vector3.MoveTowards()` will suit your use case perfectly.

Here is the sample from the documentation:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Transform target;
    public float speed;
    void Update() {
        float step = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }
}

```

---
Tags: unity, c#, transformation
---


# Question
Title: Does glScissor affect stencil and depth buffer operations?
I know `glScissor()` affects `glColorMask()` and `glDepthMask()`, but does it affect the stencil and depth buffers?

For example:

```
glEnable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glEnable(GL_STENCIL_TEST);

glScissor(X,Y,W,H);

// Is this color mask set only for the scissor area?
glColorMask(TRUE,TRUE,TRUE,TRUE);
// Does this stencil function only work within the scissor area?
glstencilfunc(GL_ALWAYS);
// Does the stencil function only work within scissor area?
glstencilop(GL_KEEP,GL_KEEP,GL_KEEP);
// Is this depth  mask set only for the scissor area?
glDepthMask(GL_TRUE);
// Does this depth function only work within the scissor area?
glDepthFunc(GL_ALWAYS);

```

# Answer
> 2 votes
The scissor rectangle applies to pixels within the depth and stencil targets, just as it does to color targets. Only pixels within the scissor rectangle will be candidates for writing, so other states controlling reading from or writing to depth/stencil targets are essentially irrelevant - they will never be read or written. For example, the depth write mask (glDepthMask) does not matter for pixels outside the scissor rectangle, because they will never be written.

---
Tags: opengl, opengl-es, depth-buffer, stencil
---


# Question
Title: How many LoD versions of a model should I have?
Many games facilitate better performance by increasing/decreasing the number of triangles/polygons that are drawn, depending on how close the camera is to said object. Mountains, viewed from far away, could become literally flat. Models would steadily lose resolution as you walk further away from them, etc.

If I want to implement such a system, how many different permutations of the same model/models should I have? Suppose the model is 20,000 triangles when viewed up close, but then I halve that when the camera goes away, so now it is 10,000. Then again, when the camera is even further away, making it 5,000 triangles. Would three versions be enough? Or is this really just an arbitrary implementation? Does it depend on the game itself?

# Answer
> 1 votes
Research the new-ish tessellation stages.

LOD and complex curved surfaces are both easy to implement with a hull shader.

**LOD example:**
A terrain, composed of 2 triangles, can be subdivided and the tessellation factor simultaneously used to select the appropriate mip for the displacement map. In this way, peaks of mountains would retain their height, but reduce to pyramid-like shapes. Tessellating more creates more, smaller, triangles and selects a higher displacement mip; the terrain becomes more accurate, on demand.

**Curve/Spline/Bezeir/NURBS**
If you tessellate a cube, then normalize all of the vertices, you've made a sphere. The more you tessellate, the more accurate the sphere. The same approach can be applied to model geometry by utilizing the curve primitives within your favorite modeling software, rather than permanently baking the tessellation into multiple copies of the same model.

# Answer
> 2 votes
This technique is called LOD (Level of Detail). Look it up and you will easily find several references on the internet.

How many levels of detail you use is completely up to you. It depends heavily on the camera's point of view, how many objects are within your viewport at the same time, and how many are so far away they are just barely visible.

Using this you should be able to decide how many levels of detail you require and how much reduction in polygons/triangles you need to have for each model to reach a decent polycount for your renderer at any possible camera point in your game.

---
Tags: rendering, performance, models, level-of-detail
---


# Question
Title: Are SDL games trivially portable from Linux to Windows?
I have a small game made with SDL2 and I want to port it to Windows. Would I hav eto write a lot of `#ifdef`s to port it or will the very same code work on Windows and Linux? Or is it more complicated?

Sorry if these are silly questions. I couldn't find existing resources on porting SDL games between desktop systems and I've never done this before!

# Answer
> 4 votes
SDL is a cross-platform library, so as long as your code is cross-platform(i.e. no OS specific calls, use '/' in directories instead of '\\', etc.), yes you should be able to copy and paste without too many issues. If you end up using a different compiler, it might be more or less lenient about certain things, but they are probably minor.

# Answer
> 0 votes
SDL can build in many Platform. If you are ussing C++, all STL library work on g++ and windows compilers. fopen, and others is the same.

EDIT: You can see this: https://wiki.libsdl.org/CategoryIO and others SDL Functions.

---
Tags: sdl, windows, c, porting
---


title: Rendering text with SDL2 and OpenGL

text:
# Question
Title: Rendering text with SDL2 and OpenGL
I've been trying to have text rendering in my OpenGL scene using SDL2. The tutorial I came across is this one Rendering text

I followed the same code, and I get text rendering fine. However the issue I'm having is that there is obviously a "conflict" between the OpenGL rendering and the `SDL_Renderer` used in the code. When I run my scene the text displays but everything else keeps flickering. The following gif shows the issue:

Any idea on how to overcome this while still just using `SDL2` and `OpenGL`, not another library or anything.

Thanks

# Answer
> 0 votes
There is a problem using SDL\_Renderer with OpenGL. You can save the text to a Surface, and then use this example: http://www.sdltutorials.com/sdl-tip-sdl-surface-to-opengl-texture

---
Tags: opengl, sdl, sdl2
---


title: Graphics, drawing triangles

text:
# Question
Title: Graphics, drawing triangles
I'm very new to the world of Computer Graphics, and I'm struggling to find resources to help me understand how to draw my mesh (I have loaded everything into vertex and index buffers), I am not using a 3D API, instead I am just using C# and a 2D Graphics canvas to draw my mesh.

Everything is currently loading, but I have suspicions that I am reading my faces in as quads instead of triangles, could somebody A) Clarify whether I am draw a quad instead of a triangle B) If I am drawing quads, how do I draw a triangle? This has been a headache for me for a few hours...

```
for (int i = 0; i < m_numFaces; i++)
{
     Face face = m_meshData[i];

     // Draw the face
     for (int j = 0; j < 3; j++)
     {
                m_graphicsContext.DrawLine(m_pen,
                     // Get the X,Y points of this face
                     (int)face.GetPointAtIndex(j).points[0],
                     (int)face.GetPointAtIndex(j).points[1],
                     (int)face.GetPointAtIndex(j + 1).points[0],
                     (int)face.GetPointAtIndex(j + 1).points[1]);
     }
                // Draw from first point back to last line
                m_graphicsContext.DrawLine(m_pen,
                     (int)face.GetPointAtIndex(2).points[0],
                     (int)face.GetPointAtIndex(2).points[1],
                     (int)face.GetPointAtIndex(0).points[0],
                     (int)face.GetPointAtIndex(0).points[1]);
}

```

# Answer
> 1 votes
You're currently drawing the following lines:

* From point 0 to point 1.
* From point 1 to point 2.
* From point 2 to point 3 (wrong!).
* From point 2 to point 0.

`j < 3` should be `j < 2`.

---
Tags: c#, graphics
---


# Question
Title: Character states in component based entity system
I'm working on a Zelda-like game (github), and I made a component-based entity system.

* I've a `Scene` class which holds a `std::vector` of `SceneObject`.
* `SceneObject` is a collection of components
* `Scene` uses systems, like `MovementSystem`, `DrawingSystem`, `CollisionSystem` to perform actions using components, or directly on components themselves. For example, this is`MovementSystem`:

```
#include "CollisionComponent.hpp"
#include "MovementComponent.hpp"
#include "MovementSystem.hpp"
#include "PositionComponent.hpp"

void MovementSystem::process(SceneObject &object) {
    if(object.has<PositionComponent>() && object.has<MovementComponent>()) {
        auto &positionComponent = object.get<PositionComponent>();
        auto &movementComponent = object.get<MovementComponent>();

        movementComponent.movement->process(object);

        movementComponent.isBlocked = false;

        if(object.has<CollisionComponent>()) {
            object.get<CollisionComponent>().checkCollisions(object);
        }

        movementComponent.isMoving = (movementComponent.vx || movementComponent.vy) ? true : false;

        positionComponent.move(movementComponent.vx * movementComponent.speed,
                               movementComponent.vy * movementComponent.speed);

        movementComponent.vx = 0;
        movementComponent.vy = 0;
    }
}

```

My problem is that I don't know how to handle states for characters.

For example, let's say Link has three states: `Standing`, `Moving` and `Pushing`.

In each state, a different animation is played, so `DrawingSystem` have to know about this, but I can't put it in a `StateComponent` because all the objects which need a state don't always need an information on animation.

In each state, I must check for conditions to change the current state and process an action. For example, if Link's current state is `Standing`, I must check if he's moving or not, to change his state to `Moving`.

Which components/system do I need to implement this?

# Answer
This type of state information seems perfect for a Controller type of component. In most implementations, you often have a PlayerController and an AIController that are derived from a common controller component. The AI system and Player system use these controllers to transition state of the associated entity.

As state transitions (standing to moving for example), you either emit an event that the animation system has hooked into or your controller system simply interacts with the aniimation system directly.

For example:

```
 void PlayerSystem::Update(float deltaTime) {

   // get the player entity's controller component.
   auto &controller = player.get<PlayerControllerComponent>();

   // crude way to handle state transition as a simple example.
   auto &velocity = player.get<VelocityComponent>();
   if(velocity.GetSpeed() != 0) {
     if(!controller.isStanding()) {
       controller.setMoving(true);
       animation.stopAnimation(player, "Standing");
       animation.queueAnimation(player, "Moving");
     }
   }
   else {
     if(controller.isMoving()) {
       controller.setStanding(true);
       animation.stopAnimation(player, "Moving");
       animation.queueAnimation(player, "Standing");
   }

 }

```

The player controller is often a good place to keep other state information like jumping, flying, or touching the ground for various other game queries.
> 1 votes

---
Tags: c++, entity-system, component-based
---


# Question
Title: How can I draw some of my XNA models semi-transparent? (C#, XNA 4.0)
I've recently made some basic Blender models without transparency for a new game I've been working on, but I'm having some problems rendering them semi-transparently. Namely, I haven't been able to figure out how to render them semi-transparent at all.

I've looked around quite a bit for code samples, and for some reason I just can't find anything that fits. I figure transparency probably has to do with BlendState.AlphaBlend somehow, but I'm not sure how exactly.

My models are simple VertexPositionColor models that consist of a single mesh. I've tried turning transparency on in the material in blender, but it doesn't seem to do anything when I render it again in C#. (Except make it appear transparent in blender) Also - I'm not looking for anything fancy like a crystal-like effect that requires making my model more than one mesh, just something simple and effective that will make my models at least able to be seen through.

So basically, my questions are:

* How can I render an opaque VertexPositionColor model at a given percent transparent?
* Is there a non-shader solution to my problem?
* Is there a code sample anywhere for doing model transparency in XNA 4.0?

Thanks!

# Answer
> 1 votes
Well, a quick Google search has turned up this small Reddit thread: http://www.reddit.com/r/gamedev/comments/1l6eiv/how\_do\_you\_render\_a\_transparent\_model\_xna\_c\_3d/

A non-shader solution isn't possible, since its the shader that is responsible for rendering the model. A non custom shader solution is, and the link above uses BasicEffect, which is XNA's defaul phong shader.

Copying the code out if the thread ever goes away.

```
public void DrawTransparent(float AlphaValue)
{
    foreach (ModelMesh modelMesh in _Model.Meshes)
    {
        foreach (BasicEffect BasicEffect in modelMesh.Effects)
        {
            BasicEffect.World = _Instance;
            BasicEffect.View = Helper.View;
            BasicEffect.Projection = Helper.Projection;
            BasicEffect.LightingEnabled = true;

            BasicEffect.AmbientLightColor = new Vector3(.3f, .3f, .3f);
            BasicEffect.DirectionalLight0.DiffuseColor = Color.White.ToVector3();
            BasicEffect.DirectionalLight0.Direction = Helper.SunDirection;
            BasicEffect.DirectionalLight0.SpecularColor = Vector3.Zero;

            Helper.GraphicsDeviceManager.GraphicsDevice.BlendState = BlendState.AlphaBlend;
            BasicEffect.Alpha = AlphaValue;
        }
        modelMesh.Draw();
    }
}

```

You'll probably have to tweak this code sample so it works with your code, but it should be enough to point you on track. The `AlphaValue` parameter is a floating point value between 0f and 1f, with 0f being fully transparent, 1f being fully opaque, and 0.5f being half transparent.

Some of the material settings in my model files don't seem to be exported across into XNA correctly - limitations of the basic Model/Effect in XNA I would assume. I've wound up with my own custom Model class and import pipeline so I can get the all the data I want from my raw model files into my custom Model Object.

Anyway, hopefully this is enough to put you on the right track.

---
Tags: c#, xna-4.0, models, transparency
---


# Question
Title: Is it possible to use one if statement for each level scene?
I'm working on a platform game where you as a player have to collect logs, to keep on all the fires in the level. Each campfire has a timer, which ensures that every x number of seconds the animation of the fire is changed to a numb fire. The timer of a campfire is blocked by the script, when the player has received the fire at 100%. When all fires are 100% you won, if not you lose.

Know I use the following if statement to check if the player has won or lose:

```
if (Application.loadedLevelName == "Level 0") {

        if (campfireAmount == allCampfireFull) {
            // Do something
            print ("level 1 complete");
            Application.LoadLevel (6);
        }

        if (campfireAmount == allCampfireEmpty) {
            // Do something
            print ("level 1 failed");
            //Application.LoadLevel ("GameOver");
        }

    }

```

What I searching for is how I can make this if statement useful for each level, whiteout use for each level scene above if statement. Beside that, what I want is that after each level you get a win scene (if possible a reusable scene) and after clicking in that scene on a button, you should go to the next level scene. Is there a way to load the next level, whiteout set a hard number of the rang list of "Build Settings"?

# Answer
You can load the "next" level with:

```
Application.LoadLevel(Application.loadedLevel + 1);

```

You will need to either:

1. Setup the last level as a non-gameplay "You Win!" scene with a different exit condition or;
2. Manually check you don't exceed `Application.levelCount`.

---

And you can count the number of objects with a given tag with:

```
int campFireCount = GameObject.FindGameObjectsWithTag("CampFire").Count();

```

If you update `campFireCount` in `OnLevelWasLoaded()` it should be easy to make a reusable script.

---

If you add the following line to your `LoadScene` script it will expose a `public static int`:

```
public static int nextLevelIndex;

```

You can then assign a value to this variable from *anywhere*, so you could include this line just before leaving a level:

```
LoadScene.nextLevelIndex = Application.loadedLevel + 1;

```

And then modify your loadScene() method to this:

```
public void loadScene() {
    Application.LoadLevel(nextLevelIndex);
}

```
> 2 votes

# Answer
if you use function pointers that are set outside of draw loop, you can use 0 if statements to act on functions for each level.

make a function that does what you need, and a pointer to that function, and swap out the function by a pointer based on what level you are on.

Pointerarray levelaction\[10\] for 10 levels using different functionality in draw loop

then just point them to the functions that are used for the level. and use the level as the index instead of a if condition.

note you get overhead of a function call, and don't get function inlined. But you get fewer ifs while having many levels.

switch statement is another option, where the compiler forms a binary tree to find the right case, making for fewer comparisons.
> 0 votes

---
Tags: unity, 2d
---


# Question
Title: Bringing islands close together programmatically
I generate island/continent maps and I want to make a grand archipelago of sorts where all these islands are located. The problem is that I don't know a **smart** way to place the islands programmatically so that the keep a minimum distance from each other. Sure, I can create a quadtree but then how do I place it? Placing it on top of another island and move it away in a random direction? I'm attaching a photo of what I want to do, easily done in Paint .NET from 6 individual maps.

The scale I'm talking about would be placing about 3-10 continents, each with a resolution of 4Kx4K upwards. (I'll only allow reflections and translations in placement, to preserve some 4-/8- connectivity pixel work that I've done for the maps)

What I'm NOT looking for:
\- a global minimum solution ( all islands as close together as possible)
\- using a heavyweight physics/maths library or tons of code
\- a super-simplistic solution either (e.g. calculate OBBs and use those to resolve collisions)

# Answer
I think you are going at the problem the wrong way. Why are you first building an island and then "place" it? I would use one algorithm to create the entire map in one go. Although the algorithm would need some tweaking, but I would some form of noise as the basis. From that I use a "water level" to defined how much and how large the land actually is. This naturally makes islands that are close to each other. To ensure that the entire map is surrounded by water increase the water level towards the edges.
> 1 votes

# Answer
Another way of doing it is create one island then introduce series of water splices... as a water is occupied on one side add land on another side.

Terrain can be done later if you lock the boundaries of land and water as soon as you're satisfied.

You can set a logic where percentage of number of island has to move greater distance than others without changing shape much like how natural continental drifts do it. There is a mathematical equation somewhere at net to compute the center of mass. Sadly it's not one of my stronger points. Using the center of islands you can tear them apart or move them closer.

Suggest to also introduce small island by taking pieces from big ones that can form as lakes.

**Moving islands while detecting with collision**. One style is make two maps. One, where islands are fix, and another where island can be moved on map. Island collision is detected when land mass overlap between two maps.

```
if Map1(x,y) = Map2(x,y)
where both have value of 1 or land mass (0 for sea)

```

You can make correction by changing shape of the island in collision by moving it on a different end or follow the coastal of another island on the fixed map. Or if you so chooses re-making the island in respect to the first map.
> 0 votes

# Answer
You need transitional states and movement to detect what point to compare distance to.

Set each point at original divide where split occurs, to a twin point at where it originally cracked apart, then always move the island based on closest twin pair.

That might work, if you keep points that must match a distance condition that are corresponding points across the ocean.

So if you set correlating points, then move those points away from each other the same number of distance, or slope of distance, they should float outward.
> 0 votes

---
Tags: collision-detection, collision-resolution
---


# Question
Title: Why do some networked games use interpolation and some use pathfinding for remote movement?
This is a bit of an open question but I'd like to see someone contribute a good reasoning for both.

For a quick example of both:

**Interpolation Model**

Think the Valve model where the client is receiving position updates frequently and the remotes update their positions using interpolation on this data.

**Path-finding**

In this model, think the user sends a destination and everyone pathfinds to it.

What types of games are suited to each and when should one use each?

# Answer
I've worked on the networking code for two real time AAA networked games, one for smartphones and one for a handheld console.

To directly answer your question "why", well, some games use one or the other because it suits them better than the other. This depends not only on the type of game, but also on what type of network we're talking about (linked arcade cabinets have different conditions compared to games that are meant to be played over 3G) Some games actually use both, or even completely different approaches to synchronize data!

I would like to generalize, and consider not only positional data, but pretty much any type of data you can synchronize between two networked clients.

Instead of two possibilities, I would like to propose a spectrum between hard and soft updates.

* **Very hard** updates are discrete events that immediately change the state on the other client, without any type of interpolation, either because the data is of critical nature (a player died), because it's not a type of data for which interpolation applies (an online chess game, chat messages, etc.), or because your network allows you to do that (think linked arcade cabinets where reliably sending the entire game state 60 times per second is well within the realm of possibility).

With this method, network delays will invariably show as delayed updates and manifest as characters jumping around.
* **Hard with inter/extrapolation** updates are similar to very hard updates, but for constantly changing data, for which it is not practically possible to reliably send the data each time it changes. Think of sending a position and a velocity vector; you should be able to interpolate data between two points, and extrapolate it after them. You should have a contingency plan if incoming data disagrees with your extrapolations. I would say most games which require position updates use this method.
* **Hard with synchronization** updates are similar to hard with inter/extrapolation, but only require synchronization rarely. You should use this for data that is really trivial to inter/extrapolate, such as the clock in a fighting game (once set on both sides, it is not really necessary to synchronize again afterwards)
* **Delayed hard** updates are similar to hard updates, but what you're seeing is data in the past. I suspect that in many music arcade games in Japan where you can play a song against somebody else, you are actually playing against player data recorded in the past, possibly hours or even days before. Of course, this type of updates are only usable when you don't really interact with the other player.
* **Soft** updates consist of sending planning data, and running the plan on all hosts. This is what you call "pathfinding". The amount of data required to synchronize data like this is much lower; you can use these types of updates when you can get away with certain discrepancies in how the data is presented to the user, like when synchronizing hundreds of enemies.

Planning data updates themselves can also be as hard/soft as you want, of course.
* **Very soft** updates are used when the outcome of an action can be reliably calculated much before it happens. You just send the result, and the other client just plays it back. For example, some browser and smartphone games let you battle other people, but the actual battle takes hours to resolve (think Travian-like games). It is very possible that these games calculate the result at the very moment the battle is initiated, and you just see the results of that battle.

Another non-networked example of this would be in Civilization 4 with battle animations enabled. When you attack somebody, the result of the battle is immediately calculated, but you get to see an animation of it playing back. I can assure you the battle is not being calculated as it is being animated.

As you can see, there are many ways to synchronize data, and I'm sure you can imagine many others. All but the simplest online games will most likely use a mixture of these methods, depending on the type of data they're synchronizing, the type of game, and even the state of the network (use hard updates when lag is low, and go to softer updates when lag gets higher).
> 48 votes

# Answer
I have no insight on Valve's development process, so this is purely my opinion, but:

**Interpolation**: I'd say it'd be better for fast paced games, like FPSs for example, where having a consistent position for an enemy on time across players is important. Interpolating means that, even if some packets are dropped (AFAIK, most multiplayers FPSs use UDP instead of TCP/IP, which guarantees neither the integrity nor the order in which the packets arrive), you will have smooth movement on the screen.

**path finding**: If time is not a crucial element of your gameplay, and your algorithm finds a consistent path when re-ran, pathfinding could be interesting because it does not require that you send frequent, and thus heavy updates with the position of each single entity. I'd say this seems fitted for a turn based system for example, where you can then limit the amount of network requests (one at the beginning of the turn, one when the turn is over to make sure all clients are in a "sane" state.

Once again, I've never worked on a network game or for a big game studio, but from what I've read sometimes that's how I would go about it :)
> 3 votes

# Answer
Panda Pajama answer is pretty good.

Basically the question comes down to what is the minimal amount of data you can send that will put multiple clients in the same awareness of each others state, and how do you handle the lag where during that lag clients might be in a different state.

So procedurally generated, where all the interactions are known before hand is easiest, since if all variables are known then the outcome is known. For example isolate someone in a room, that you know the processing methods of, and give him some set of data, you can accurately predict the results. Therefore you can give every other client the results without having for them to wait for that client to finish his calculation.

However he did not mention one method. Forced results.

If the system expects an action by some entity, and other actions are dependent on that action, and other calculations take into account that action, and have already been preprocessed with that result that is expected. Then to maintain synchronization, the entire system is stopped while the one entity that is not in the right place is correctly put back on his path.

A real world example is all other entities in a holding pattern to make sure the proper compensation is sent to me.
> 0 votes

---
Tags: networking, path-finding, interpolation
---


title: How to cast colored shadows

text:
# Question
Title: How to cast colored shadows
I have a glassy object and when light passes through it I want it to cast colored light behind it, instead of the shadow.

I could just use another light object to cast that colored light, but is it possible to do this using shaders?

# Answer
> 2 votes
Treating them like shadows should work fine.

-Render the world from the light(s) perspective(s) and record the distance from the light.
-Render the world from the camera's point of view, then sample and compare the new distance.
-For each pixel, if the world-space pixel-to-light distance is greater than the light-space pixel-to-light distance, the pixel is in "shadow".
-You can mix the glass color in, any way you'd like. Glass usually perturbs light that passes through it.

A perturbation texture, color texture, and/or stencil can also be used to enhance the effect. For example, sampling a "stained glass" texture when coloring the final pixel, will project the stained glass effect onto anything it hits. "Frosted" glass, "privacy glass", glass-block walls, panes with beveled edges, etc., etc.; all from textures.

For the lightmap render, the length is just:

```
length(lightPos - worldPos)

```

Write the value to the lightmap. For the camera render, you'll need to calculate the camera-space length using length(), sample the light-space length out of the lightmap, and compare.

To retrieve the light-space length during the camera render, project worldPos using the light's (View * Projection) matrix. The resulting coordinates range from -1 to +1 and need to be scaled into the 0 to 1 (UV) range. UV's place (0,0) at the top left which corresponds to screen-space (-1,+1) so you'll need to invert the Y. With the UV coordinate, sample the lightmap for the length, then subtract the two lengths.

```
lightUV = mul(float4(worldPos, 1), lightVP);
lightUV += 1;
lightUV /= 2;
lightUV.y = 1 - UV.y;

```

For simple colored glass, sample the object textures as usual. If the pixel is in shadow, multiply the sampled color by the light's color.

lightVP, lightColor, lightPos will probably all be in a constant buffer
worldPos will need to be saved by the vertex shader and passed to the pixel shader

---
Tags: unity, shaders, lighting
---


# Question
Title: Unity 2D: Sprites/Diffuse is making my character weird, like an antialias
i'm trying to put light and shadows on my 2D character but when i set the material on it to Sprites/Diffuse, it's kinda putting a strange smooth on my pixels.

Without diffuse:

With diffuse:

And i saw that with diffuse it doesn't appear any shadow, it's normal?

# Answer
> 0 votes
Well, I found how to fix. You have to recreate the project, and then before put all the sprites together, you have to unmark Generate MipMaps and change filter mode to point. Do this without creating a new project(inside of the project already done) didn't worked. Then after replacing all the slices, you put the material with Sprites/Diffuse.

---
Tags: unity, 2d, sprites, lighting
---


# Question
Title: Compressing language for Game use to save Packets
Given ASCII is 8 bits (1 byte), UNICODE is 32 bits (4 bytes).

An idea came to my mind to support multiple language by isolating certain UNICODE Letters to support multiple language for my chat(game) program.

It will be composed of \[4 bit (Language trigger)\] + \[8 bits (255 possible characters) x 16\]

Example:

```
trig|message per character, each 8 bit is character depending on trigger, language changes
0001|00000000|00000000|00000000|00000000|00000000....

```

Trigger for characters: (example purpose only)

```
0001 Normal Latin
0010 European Latin
0011 Historic Latin
0100 Japanese
0101 Chinese
etc...

```

The characters at UNICODE not present at my list will make a special character... I'm thinking a Box (which will be present at the 0001 character list).

My in-built character table will supply the character depending on the trigger. Of course the User can only use one set of trigger and not mixed character using different triggers.

I also want to use this character for my Account Server Creation and Queries. Note that other character format do not support multi-language characters.

**Result Comparison:** Instead of sending 512 bits (32 bit x 16). I am actual sending 132 bits (4 bit + (8x16)) only.

Is this feasible and currently in use or am I doomed to use UNICODE? I am open for better ideas than the ones above.

# Answer
> 2 votes
Here are 2 common ways games save space when communicating strings over the network or serializing to disk.

1. Zlib the text or use some other compression algorithm (even just Huffman compression). You can compress the text with a pre-shared compression header so that the header doesn't add to the size.
2. If there are common strings you have to send or serialize, have each game client have a built in string table of these strings and have it send the index into the string table (one uint32) instead of the string itself. Side benefit is that this sets you up nicely for localization as well (having your game run in multiple languages). Some games also have a dynamic table that can be added to at runtime and have ids starting at the last static string id, for the cases where new strings can be needed that are hard to predict in advance.

Also, like other folks have suggested, use utf-8 encoded strings! (:

---
Tags: compression
---


# Question
Title: How do I prevent clicking at the end of each sound play in OpenAL?
I have put together a basic sound handler class for use in my game. It uses OpenAL.

It's a simple method at the moment to play sounds - here's an extract from a switch block:

```
case "EATEN_PILL":
    wavPath = "D:\\Programming\\SFX\\EATEN_PILL\\Hit_43.wav";
    ALfilename = Path.Combine(Path.Combine("Data", "Audio"), wavPath);
    sound_data = LoadWave(File.Open(ALfilename, FileMode.Open), out channels, out bits_per_sample, out sample_rate);
    buffer_EATEN_PILL = AL.GenBuffer();
    AL.BufferData(buffer_EATEN_PILL, GetSoundFormat(channels, bits_per_sample), sound_data, sound_data.Length, sample_rate);
    AL.Source(source, ALSourcei.Buffer, buffer_EATEN_PILL);
    AL.SourcePlay(source);

    break;

```

Problems: 1. An annoying click at the end of each sound. 2. Eventually sound stops playing completely. This is after perhaps playing 100 sounds.

Has anyone hit this problem before?

# Answer
> 13 votes
# This is probably the solution for most of the clicking sounds from OpenAL-Soft library.

Might be too late after more than year for the person who posted the question but might be useful for others who end up here through Google.

I had the same problem of hearing clicks at the end of loops so I tried to figure out where it is coming from. While trying different things I realized that when I create some waves dynamically, there are no clicks being heard but loading the files will result in clicks so I guessed that there are some extra bytes loaded while loading the files that produces the click so I took a look at the wav file spec here:

PCM/WAVE file spec

and found the proper header including the data length and instead of loading the whole data after the header, **just loading the amount of bytes mentioned as the data length in the header will fix the problem!**

*I leave my code snippet here for everyone to take a look and I'm sure it will solve the problem for many developers. ;) :D*

```
    public void BufferData(Stream audioDataStream)
    {
        if (audioDataStream == null)
        {
            throw new ArgumentNullException("audioDataStream");
        }

        using (BinaryReader reader = new BinaryReader(audioDataStream))
        {
            // RIFF File Marker
            string signature = new string(reader.ReadChars(4));

            if (signature != "RIFF")
            {
                throw new NotSupportedException("Specified stream is not a wave file.");
            }

            //Size of the overall file
            reader.ReadInt32();

            // WAVE File Type Header
            string format = new string(reader.ReadChars(4));

            if (format != "WAVE")
            {
                throw new NotSupportedException("Specified stream is not a wave file.");
            }

            // 'fmt ' Format chunk marker (Includes trailing null)
            string formatSignature = new string(reader.ReadChars(4));

            if (formatSignature != "fmt ")
            {
                throw new NotSupportedException("Specified wave file is not supported.");
            }

            //Length of format data as listed above
            reader.ReadInt32();

            //Type of format (1 is PCM)
            reader.ReadInt16();

            //Number of Channels
            int channels = reader.ReadInt16();

            //Sample Rate
            int sampleRate = reader.ReadInt32();

            //(Sample Rate * BitsPerSample * Channels) / 8
            reader.ReadInt32();

            //(BitsPerSample * Channels) / 8
            reader.ReadInt16();

            //Bits per sample
            int bits = reader.ReadInt16();

            //"data" chunk header, Marks the beginning of the data section
            string dataSignature = new string(reader.ReadChars(4));

            if (dataSignature != "data")
            {
                throw new NotSupportedException("Specified wave file is not supported.");
            }

            //Size of the data section
            int dataLength = reader.ReadInt32(); // <========== **The correct data length**

            ALFormat audioFormat = getAudioFormat(channels, bits);

            byte[] audioData = reader.ReadBytes(dataLength);

            AL.BufferData(ID, audioFormat, audioData, audioData.Length, sampleRate);
        }
    }

    private ALFormat getAudioFormat(int channels, int bits)
    {
        switch (channels)
        {
            case 1: return bits == 8 ? ALFormat.Mono8 : ALFormat.Mono16;

            case 2: return bits == 8 ? ALFormat.Stereo8 : ALFormat.Stereo16;

            default: throw new NotSupportedException("The specified sound format is not supported.");
        }
    }

```

# Answer
> 1 votes
You are leaking memory each time a sound is being played.

You might consider:

* Making a class for a `SoundBuffer`.
* Loading all sounds after OpenAL is initialized (after you have created the `AudioContext` object)
* Keep in mind that a `SoundBuffer` is an unmannaged resource.
* Implement **Disposable pattern** for `SoundBuffer` and call `Dispose` once the resource is no longer needed.
* You could also simply store an array of buffer IDs and release them afterwards with `AL.DeleteBuffer(BufferID)` or `AL.DeleteBuffers(BufferIDArray)`

# Answer
> 0 votes
If you are doing everything correctly and there's still clicking (a definite possibility if the sound file doesn't end in faded to silence at amplitude 0), the way in general to address the problem is to fade it out to silence over the last 20 milliseconds (exact length of fade can be tuned to your needs). If you have popping in the beginning, you can solve it similarly by fading in from silence over a short period of time. These fades are called envelopes and are a common solution to the problem (:

---
Tags: c#, game-design, sound-effects, opentk, openal
---


# Question
Title: How to generate a RGB * a texture for a glow effect in GLSL?
I would like to create a glow effect in GLSL, there is a tutorial that explains how we multiply RGB * a :

I have some questions :

is it an operation that is in a fragment shader, where RGB*a is calculated each frame, and then we apply the blur at the end of the shader? The whole process in the same shader, called each frame? Or can we multiply RGBa in a separate process at the beginning of the game and send this texture to the fragment that will blur the result*?

I have tried to translate the informations I found, but I am a beginner with the shaders, could someone put me on the right track here? Should we use a "buffer"? Here is my starting code :

```
GLuint CreateBufferForMixAB() {

    unsigned char * data;
    GLuint bindingPoint = 1, mixTex, buffer;

    glGenTextures( 1, &mixTex );
    glBindTexture( GL_TEXTURE_2D, mixTex );
    data = (unsigned char *)malloc( width * height );
    ...imageTex.rgb * alphaTex.rgb...

    glGenBuffers(1, &buffer);
    glBindBuffer(GL_UNIFORM_BUFFER, buffer);
    glBufferData(GL_UNIFORM_BUFFER, sizeof(mixTex), mixTex, GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, buffer);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
    GL_UNSIGNED_BYTE, data);

}

```

Thanks

# Answer
> 2 votes
In order to do a glow or bloom, you generally need to start with an image, threshold it and possibly colorize it, then blur it and add the blurred version to the original. I would do this by creating a few textures and FBOs for multiple passes. Something like this pseudocode:

```
Create an FBO
Attach a texture to it to draw into
Draw a textured quad with your input image as the texture and a shader applied
    that makes every pixel with a luminance below some threshold transparent black
    (that is the RGBA = 0,0,0,0). All other pixels are either left untouched
    or their color is pulled out of a gradient texture based on their luminance
Detach the texture, and attach a new output texture to the FBO
Apply a horizontal blur to the thresholded image (Do this by drawing a textured quad
    with the threshold image and applying a shader that blurs horizontally)
Detach the blurred texture and attach a new output texture to the FBO
Apply a vertical blur to the horizontally blurred image (using a shader as above)
Detach the vertically blurred texture and attach the final output texture
Add the original unmodified input texture to the vertically blurred texture either
    using a shader or using blending

```

A shader for doing a threshold might look something like this:

```
in vec2 texCoord;
out vec4 color;
uniform float threshold;
uniform sampler2D inputImage;
const vec4 lumConst = { 0.2126, 0.7152, 0.0722, 0.0 };
void main ()
{
    vec4 inputSample = sample (texCoord, inputImage);
    vec4 result;
    if (dot (inputSample, lumConst) < threshold)
    {
        result = vec4(0.0);
    }
    else
    {
        result = inputSample;
    }
    color = result;
}

```

A horizontal or vertical blur would sample some number of pixels to the left and right or above and below the current pixel and multiply them by kernel weights and sum them.

To get more bloom, you can scale the final blurred image by a value greater than 1 before adding it to the original image.

---
Tags: opengl, shaders, glsl, fragment-shader, glow
---


# Question
Title: Grayscale color mode texture not rendering in libGDX
I am about to develop a game completely in shades of grey using libGDX and just for testing purposes, i created two textures in photoshop:

1. 2048 x 2048 plain white png image with **RGB** color mode of size **19.1**KB
2. 2048 x 2048 plain white png image with **grayscale** color mode of size **7.67**KB

... so basically both are just plain white images to look at, but the GREY.png one takes comparatively less space than the RGB.png. While rendering the both the images one at a time, RGB image renders perfectly but the **grayscale one does not render at all and the output is completely black**. My code:

```
@Override
public void create() {

    texture = new Texture (Gdx.files.internal ("GREY.png")); // ...just change to "RGB.png" to render RGB.png image..
    batch = new SpriteBatch ();

}

@Override
public void render() {

    Gdx.gl.glClearColor (0, 1, 0, 1);
    Gdx.gl.glClear (GL20.GL_COLOR_BUFFER_BIT);

    batch.begin ();
    batch.draw (texture, 0, 0);
    batch.end ();

}

@Override
public void dispose() {
    texture.dispose ();
}

```

This is all it...No cameras are used, just 2 lines in create() and 5 lines in render() method and 1 line in dispose() method, nothing fancy at all...

**Also it will be really stupid to load 19.1KB texture and render it in greyscale using shader when you can directly load same looking image of 7.67KB size**.

I don't understand why libGDX does not render the image with grayscale color mode, is it not supported?

**UPDATE:** grayscaled images are supported by libGDX and

```
 texture = new Texture (Gdx.files.internal ("gs.png"), Pixmap.Format.LuminanceAlpha, true);

```

solved my problem.

# Answer
> 1 votes
There are overloads for Texture() that allow you to pass a Pixmap.Format. The list of formats is quite limited.

Per OP:
texture = new Texture (Gdx.files.internal ("gs.png"), Pixmap.Format.LuminanceAlpha, true);

---
Tags: android, libgdx, textures
---


# Question
Title: Simple way to shoot bullets from a ship at angles for shoot em up
Just like the title says. I'm working on a shoot em up for a personal project, and I can't seem to get this to work. I don't have any code for it, but I do have the code to make my ship shoot, but that's pretty straight forward mumbo jumbo. I have seen people use the Math function for this, but any help would be appreciated.

# Answer
I have answered this before, not that difficult, although this method is only as accurate in relation to how many points, perfect accuracy is when the number of points you use reaches infinity.

have a vector that is the flying bullet, it starts at exit of muzzle with a direction and speed.

have a vector of gravity, a vector of air resistance. have a force of gravity

decide how many points you want based on how many seconds you want to have between location checks.

Then for every point move object direction it was heading from its last vector using speed and time between points and movement vector of object.

Then for the next point Change its speed based on air resist by applying that vector Change its directional vector(or altitude? see what works best) by the gravity vector. And change the gravity vector(so it is accurate for next calculation) by using the next level derivative of acceleration that gravity has. Gravity accelerates so each step it is a larger vector then step before. (then if you expect fast falling objects apply air resistance to gravity vector also so things like terminal velocity will have a emulated effect)

Then find that next point, and next, and next, by iterating over all the points until collision detection hits another ship or water. This is also how ships can calculate firing angles before shooting a shell for them to land at a specific target.

You also can precompute where at some angle, and some shell mass and speed, where that shell will land, then use a look up to a table of precomputed landing location at same altitude. Table can also include a set of points for animation.

The only thing that changes the impact location (if not calculating with windage effects) is starting velocity, air resistance effect(based on shell mass) and starting speed. So if you are using the same shells in computation, a table of points will always be the same for every angle.

if your using many different speeds like how far you pull back a bow, you could make a table with entries for angle and power(^2 table size though), and then have to interpolate between any two points in the stored array to find accurate points, since there are so many more entries precision of each entry could be less, or table would be much larger.
> 1 votes

# Answer
Here's the simplest math function for velocity based objects utilizing parametrics.

```
x += cos(theta);
y += sin(theta);

```

The end. It's really quite simple because speed is a scalar, but we want speed and direction, in essence, a vector -VELOCITY, thus we end up splitting our speed vector into x and y components as needed by a dimensional object.

You can apply this to a wide range of physics based equations too!

```
DisplacementY = .5 * acceleration * time^2 + initialYVelocity
DisplacementX = velocity * time

```

P.S. if you use the above equation for gravity, I wouldn't accelerate too much or it'll make collisions kind of buggy (that's why fast moving objects in game sometimes end up in a wall or going straight through them).
> 1 votes

# Answer
Since this is a top down shooter, and you have the basic shooting done, here is a 5 minute piece of (untested) incomplete code that allows for the creation of bullets at different angles.

```
public class Bullet
{
    protected Texture2D texture;
    protected Vector2 position;
    protected Vector2 angularVelocity;

    /// <summary>
    /// Defines a bullet.
    /// </summary>
    /// <param name="bulletTexture">Texture for the bullet.</param>
    /// <param name="bulletOrigin">Position the bullet will originate from.</param>
    /// <param name="bulletSpeed">Speed of the bullet.</param>
    /// <param name="bulletAngle">Angle of the bullet (in radians).</param>
    public Bullet(Texture2D bulletTexture, Vector2 bulletOrigin, float bulletSpeed, float bulletAngle)
    {
        texture = bulletTexture;
        position = bulletOrigin;
        // create our angle from the passed in angle
        Vector2 angleVector = new Vector2((float)Math.Cos(bulletAngle), -(float)Math.Sin(bulletAngle));
        // multiply the angle vector by the bullet to get its angular velocity (velocity on some angle*)
        angularVelocity = angleVector * bulletSpeed;
    }

    public void Update(GameTime gameTime)
    {
        // time since last update
        float delta = (float)gameTime.ElapsedGameTime.TotalSeconds;
        // multiply the angular velocity by the time elapsed for delta correction (unstable framerate)
        // then add it to the position
        position += angularVelocity * delta;
    }
}

```

Its not terribly complex (and probably isn't accurate), but basically you create a bullet with a specified texture, origin, speed and angle and update it every turn (possibly with a manager of some sorts).

I've commented the code, so hopefully its enough to demonstrate how to go about firing bullets off on an angle for that wonderful 7 barreled, 135 degree cannon that shoots EVERYTHING on the screen, except for the 225 degree blind spot to your sides and behind you (You do have one of those, right?)

`*` I could have given this variable a better name, but then it would have taken more than 5 minutes
> 1 votes

---
Tags: xna, c#, game-mechanics, angles, shoot-em-up
---


# Question
Title: How to handle transparent pixels in a spritesheet
I am trying to correctly handle transparent pixels. I have a spritesheet that gave me the following:

The green body is the ground physics body and the gray body around the sprite is the sprite's physics body - calculated with the bounds of the sprite. I plan on having images for the ground body of the same size, and wanted the sprite's feet to touch the ground. I was able to achieve this by repacking the images in a new spritesheet with TexturePacker, without any transparent pixels:

However, now my problem is other animations, like crouch for example:

As you can see, the sprite's feet are once again off the ground. Doing this animation in the game looks silly because the sprite crouches by lifting his feet off the ground body.

The output metadata in JSON from TexturePacker looks like this:

```
{
    "filename": "Crouch/soldier_crouch_1.png",
    "frame": {"x":712,"y":867,"w":353,"h":425},
    "rotated": false,
    "trimmed": true,
    "spriteSourceSize": {"x":49,"y":42,"w":353,"h":425},
    "sourceSize": {"w":433,"h":500},
    "pivot": {"x":0.5,"y":0.5}
},
// ...

```

This is a problem for several of my animations with this and other sprites. Repacking with TexturePacker allows me to remove the transparent pixels and have a more accurate physics body (which was really the goal, I'd like the most accurate collision detection once I start having projectiles) but now the animations look funny.

How is something like this handled in game development?

# Answer
I don't think it is a good idea to mix logic and art; or more precisely, base your logic on your art. In simpler terms, don't do what you're doing. Separate logic from art.

The idea behind this is that the person who draws the sprites should be able to do any kind of drawings and change them at will, without having to worry that artistic changes will have an effect on the logic of the game.

Instead, I recommend you define a sprite size, and a logical origin (baseline and horizontal center), which is constant for all sprites (or explicitly defined for each sprite), regardless of what the pixels look like; then, you base all your logic around those numbers, not on what the sprites look like.

The logical origin is pretty much where the sprite touches the floor. This is not necessarily the lowest pixel, as it may be possible to have drawings where the character does intersect the ground. Also, not always the lowest pixel will be the character's feet: a running animation may have frames in which no feet are touching the ground.

It is also useful for the origin to contain a horizontal center. You could use this as a pivot when turning the character to the opposite direction. This is not necessarily the actual center of the sprite: a sprite of a jousting knight with a long lance pointing right could have a horizontal center placed all the way to the left.

Additionally, you may want to include other points of interest in your specification, such as where the top of the head is when jumping (for top collisions), where the action point is (like the tip of the lance in our jouster), or where any collision points are (for damage taking and stuff). All this is called the *technical specifications* for your art. This should obviously be discussed with the artist.

If the artist also respects these specifications, you should not have the problem you're having, the artist can change the sprites at will, and not worry that any changes will affect the logic of the game.

The main advantage of working in this manner is consistency, but also you can get rough sprites so you can work on the game, and then replace your sprites with the final ones. This workflow is much easier to work with.

Then, if you want you can make the sprites take less space in your spritesheets, you can trim the transparent pixels out, but you should then make any necessary coordinate corrections for when this happens.
> 1 votes

# Answer
If you arent going (or can't because of software limitations) to remove the extra pixels you could go into the original sprite sheet and move the image of the crouching soldier down.

The problem is that you won't have accurate collision detection if you are keeping those extra pixels so crouching might be useless.
> 0 votes

# Answer
you can simply use the box2d editor to match your sprite sheet with the body fixture there is a powerful application who do this for you :

**LINK**

you can :

* Automatically decomposes concave shapes into convex polygons,
* Automatically traces your images if needed,
* Supports multiple outlines for a single body,
* Supports polygon and circle shapes,
* Reference point location can be changed,
* Visual configurable grid with snap-to-grid option,
* Built-in collision tester! Throw balls at your body to test it,
* Loader provided for LibGDX game framework (written in Java),
* Simple export format (JSON), to let you easily create your own loader for any framework in any language.
> 0 votes

---
Tags: javascript, sprites, box2d, spritesheet, easeljs
---


title: How BufferStrategy works

text:
# Question
Title: How BufferStrategy works
I've used this piece of code a lot in my games, but I still don't know exactly how it works.

```
 // Main loop
while (!done) {
     // Prepare for rendering the next frame
     // ...

     // Render single frame
    do {
        // The following loop ensures that the contents of the drawing buffer
        // are consistent in case the underlying surface was recreated
        do {
            // Get a new graphics context every time through the loop
            // to make sure the strategy is validated
            Graphics graphics = strategy.getDrawGraphics();

            // Render to graphics
            // ...

            // Dispose the graphics
            graphics.dispose();

            // Repeat the rendering if the drawing buffer contents
            // were restored
        } while (strategy.contentsRestored());

        // Display the buffer
        strategy.show();

        // Repeat the rendering if the drawing buffer was lost
    } while (strategy.contentsLost());
}

```

Why should I use those two do-while loops? What does it achieve? Well, I know why because of the comments, but I want to know exactly what happens

BufferStrategy: http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferStrategy.html

# Answer
> 1 votes
BufferStrategy will often use VolatileImage for the buffer. Part of the use case of volatile image is that its backing buffer may be lost without warning. This require you to rerender to the volatileImage.

What you can do as an optimization is test both `contentsLost` and `contentsRestored` inside the inner while loop and repeat the loop using `continue` if either are true (disposing the graphics object as needed):

```
Graphics graphics = strategy.getDrawGraphics();
try{
    background.render(graphics);

    if(strategy.contentsRestored() || strategy.contentsLost()){
        continue;
    }

    renderEntities(graphics);
} finally {
    graphics.dispose();
}

```

---
Tags: java, game-loop
---