title: Loading levels in XNA from XML

text:
# Question
Title: Loading levels in XNA from XML
I'm trying to load levels in XNA from XML files. I have currently got a system to do this working, but it looks like it might get horribly complex as I add more objects later on. My world currently consists of `Planet` entities along with physics props, scenery, static props, etc. It will later include NPCs, interactive machines, and a *lot* more content (but I want to sort this out before going any further).

Based on a tutorial I read, my level loader loads a `LevelData` entity from XML. This contains arrays of `PlanetLevelData`, `PropData`, and `StaticData`. My test file is as shown:

```
<?xml version="1.0" encoding="utf-8" ?>

<XnaContent>

<!-- TODO: replace this Asset with your own XML asset data. -->

    <Asset Type="DataTypes.LevelData">`

        <PlanetData>
            <Item>
                <Position>5.2 5.2</Position>
                <BodyRadius>300</BodyRadius>
                <FieldRadius>450</FieldRadius>
                <Name>Jupiter</Name>
                <Rotation>0</Rotation>
                <ImageName>-</ImageName>
            </Item>
            <Item>
                <Position>-2 -2</Position>
                <BodyRadius>300</BodyRadius>
                <FieldRadius>450</FieldRadius>
                <Name>Jupiter2</Name>
                <Rotation>0</Rotation>
                <ImageName>-</ImageName>
            </Item>
        </PlanetData>

        <PropData>
            <Item>
            <Type>Crate</Type>
            <Position>2 3</Position>
            </Item>
        </PropData>

        <StaticData>
            <Item>
                <Type>FromImage</Type>
                <Position>-4.5 -4.5</Position>
                <ImagePath>Lamp</ImagePath>
                <Rotation>2</Rotation>
                <Radius>0</Radius>
                <Vertices></Vertices>
                <PlanetOwner>Jupiter2</PlanetOwner>
            </Item>
        </StaticData>

    </Asset>

</XnaContent>

```

In other words, I have to put *all* my content files into arrays. However, for me to have different types of `StaticData` from the XML file, I have to specify the type with a String (called `Type`).

I then load the XML using `Content.Load<LevelData>("name here.xml")`. I go through every `PlanetData` in the array and create a new `Planet` based on it's properties. I also use switch statements based on the `Type` field to specify which type to create...

Is this the only way to load level data into objects using XML (I hope not, it's hideous to use). I couldn't really find much on this topic...

# Answer
> 4 votes
The content project supports XML files, and it uses a special type of serializer called IntermediateSerializer, which is better suited for game data than XmlSerializer.

No need to read your PlanetData and figure out how to convert it to a Planet, you can directly serialize a Planet and have it seamlessly loaded at runtime. In your editor, you can create a Planet object and serialize it to XML:

```
Planet Jupiter = new Planet();
Jupiter.Position = new Vector2(5.2, 5.2);
Jupiter.BodyRadius = 300;
Jupiter.FieldRadius = 450;
Jupiter.Name = "Jupiter";
Jupiter.Rotation = 0;

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using( XmlWriter writer = XmlWriter.Create( "Jupiter.xml", settings ) )
{
    IntermediateSerializer.Serialize( writer, Jupiter, null );
}

```

This serializes an individual Planet object called Jupiter.xml that you can load with your content manager just like you would load a texture or a model. Include it in your content project and call the following code at runtime:

```
Planet jupiter = contentManager.Load<Planet>( "Jupiter" );

```

If you want to serialize a single Level object containing all of your actors, just fill out your Level class with its members and serialize the Level object in the same fashion. When you load the Level object it will already be filled with all of the appropriate objects.

Shawn Hargreaves has an excellent series of posts on the IntermediateSerializer, under the "IntermediateSerializer" heading:

http://www.shawnhargreaves.com/blogindex.html

# Answer
> 5 votes
There may be a way to do this with the content pipeline, but I have done it without and instead used standard XML Serialization.

The approach I am about to show is just one way you can structure your data and may or may not be relevent to what you are trying to accomplish. My goal with this answer is to provide you enough direction so that you will be able to create your own level structure and apply it to your game.

To start with I have an XML file in my content project that looks something like this:

```
<?xml version="1.0" encoding="utf-8" ?>
  <Screen>
    <TileSet Width="16" Height="16">
      <Tiles>
        <Tile GroupId="G" TileId="1" TextureName="Generic" Path="tempSprites/Terrain" X="9" Y="3" />
        <Tile GroupId="G" TileId="2" TextureName="Generic" Path="tempSprites/Terrain" X="10" Y="3" />
        <Tile GroupId="G" TileId="3" TextureName="Generic" Path="tempSprites/Terrain" X="11" Y="3" />
      </Tiles>
    </TileSet>
    <ScreenDefinition Width="40" Height="24" BaseGroup="G">
      <TileReferences>
        <TileReference Id="G2" X="0" Y="0" />
        <TileReference Id="G3" X="15" Y="0" />
        <TileReference Id="G2" X="15" Y="15" />
        <TileReference Id="G3" X="0" Y="15" />
      </TileReferences>
    </ScreenDefinition>
  </Screen>

```

All XML Attributes and sub elements you see are properties within the object class.

So following this, Screen is our root elemment and is a class within my project. This class contains a TileSet object property and a ScreenDefinition object property. The code for this class is as follows:

```
[XmlRoot()]
[Serializable]
public class Screen
{
    public Screen()
    {
    }

    [XmlElement]
    public TileSet TileSet;
    [XmlElement]
    public ScreenDefinition ScreenDefinition;
}

```

TileSet looks something like this:

```
[Serializable]
public class TileSet
{
    public TileSet()
    {
    }

    [XmlArray]
    public List<Tile> Tiles { get; set; }

    private int width = 0;
    [XmlAttribute]
    public int Width
    {
        get { return width; }
        set { width = value; }
    }

    private int height = 0;
    [XmlAttribute]
    public int Height
    {
        get { return height; }
        set { height = value; }
    }
}

```

The key part of this class is the `[XmlArray]` attribute on the Tiles property. This is what helps define that object to be deserialized into a collection of Tile objects when loaded.

The rest of the data classes I will not show because they follow the same general pattern that you have seen here with these two classes.

To implement this it is incredibly painless. First you need to do some configuration to your XML file so that its not processed by the content pipeline.

1. In Solution Explorer, click your XML file
2. From the properties window, Set the Build Action property to "None"
3. From the properties window, set the Copy to Output Directory property to either "Copy always" or "Copy if new" (whatever fits your needs)

This sets us up so that you can access the XML file right from the file system. Assuming you added the XML file to a Content project the file will be in the `bin/Content/Your/Folder/Structure/Here` folder.

Now you are ready to actually load the data from the file, and its as easy as this:

```
XmlSerializer serializer = new XmlSerializer(typeof(Screen));
StreamReader reader = new StreamReader(filePath);
Screen screen = (Screen)serializer.Deserialize(reader);
reader.Close();

```

Anywhere you see the type "Screen" is going to be what you've defined as your root element in your XML file and in code (see the `XmlRoot()` attribute on the Screen class).

And with all of this you should be able to dynamically load all your XML data into objects at run time. The data setup can be tedious depending on your data structure but it works really well once you learn the ins and outs and all the caveats of serialization.

# Answer
> 3 votes
There's definitely ways to make this a lot less tedious.

1. Your level file should describe the entities and their relationships in the world, so that when you deserialize the XML through ContentManager.Load, you get a Level instance that is ready to use. No additional processing needed.
2. The reason you find it tedious is because you are MANUALLY adding all the content in the XML file. What you should be doing instead is simply adding all the stuff in the editor like usual and then simply let the IntermediateSerializer do the work for you when you save the level.

```
var xmlSettings = new XmlWriterSettings
{
        Indent = true,
        IndentChars = "\t",
        NewLineChars = "\n"
};

var destinationFileName = "[DestionFilename]";
using (var outputFile = XmlWriter.Create(destinationFileName, xmlSettings))
{
        IntermediateSerializer.Serialize<SceneGraph>(outputFile, scene, destinationFileName);
}

```

This can then be loaded using step1.

NOTE: The SceneGraph above is my "Level".

UPDATE:

@WilliamOsborne They are loaded like any other object. InterMediateSerializer automatically adds the Type attribute when serializing and loads the appropriate type when deserializing.

Assume that your Galaxy has a list of astronomical objects in a list:

```
    class AstronomicalObject { .. }         //Base class
    class Planet : AstronomicalObject { .. }
    class Asteroid : AstronomicalObject { .. }

    class Galaxy
    {
        public List<AstronimicalObject> AstronomicalObjects
        {
            get;
            set;
        }
    }

```

When the Galaxy is serialized the output will look something like this:

```
    ...
        <AstronomicalObjects>
            <Item Type="Planet">...</Item>
            <Item Type="Planet">...</Item>
            <Item Type="Asteroid">...</Item>
        </AstronomicalObjects>
    ...

```

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


# Question
Title: How to setup a client to work with a remote server or a local included server?
I'm working on a Networked multiplayer game, but while developing and for testing I want to set up a local server that acts like the multiplayer server.

My thought is to approach the server as a proxy setup. Creating a class that the client sees and essentially allowing it to either load the server code in itself or to use a networking layer.

Is this a good approach? Are there other approaches to look into? What pitfalls should I be watching for?

**Update**

A bit more specifically I need to do this because I am targeting the Ouya and I can't guarantee a network connection, or even a spare machine to run the server on. And inside Android it is more difficult to setup and launch a service rather than include my server code right into a client build.

# Answer
In my experience, I would suggest you start with a networking layer, right out of the gate. Connecting to a network (and the issues related to it) are worth confronting head on. Since it's a multiplayer game, you're going to want to start facing those issues early (and often).

Further, my recommendation would be to develop your server code, run it locally, and when you're ready, move it to its real location. In other words, rather than think of the server as merely a temporary solution for testing, think of it as the ultimate solution in a temporary location, otherwise you're going to be developing the server code twice.1 If you're running your server on the same computer as your emulator, you can just connect to localhost. Even better is to connect to your IP address (the external one, seen from outside your network), and then set up port forwarding of whatever ports your game communicates over to send the packets to your server computer. With that setup you can still test with a reasonable number of people without raising the ire of your ISP.

As far as where the codebase "lives," my suggestion would be: do NOT include the server code in your client codebase. Advantages include:

* It keeps the client smaller. (Which is good, since users don't like bigger downloads)
* It keeps the server code away from those who would decompile the client to hack your game.

Nonetheless, there will likely be a need for some classes to be shared between the client and server. That's why I recommend that you DO include the client code in your server codebase. Classes that are common to both the client and server can live on the client side. (Alternatively, you could have three codebases: (1) server; (2) client; and (3) shared, but I don't think that's necessary, since the server having extra code it doesn't need from the client isn't a big deal.)

1For my project, I used KryoNet and can't recommend it enough. It's a very simple, clean, open source client-server solution, written in java.
> 4 votes

---
Tags: software-engineering, networking, multiplayer, server, ouya
---


title: update image properties

text:
# Question
Title: update image properties
Is there a way to update the location of an image?

I'm currently calling my image dynamically using:

```
itemImage = display.newImage(inventory[t.ID][1])

```

t. being my target ID.

But in order for Storyboard to properly work, I need to change its location in my code to above my function, rendering its dynamic properties useless. Is there a way to update it like you can do with .text?

something along the lines of:

```
itemImage.image(inventory[t.ID][1])
itemImage.imageUpdate(inventory[t.ID][1])

```

etc...

# Answer
No. You have two options.

Firstly, you can remove the image and then request the next one.

```
display.remove(itemImage)
itemImage = nil
local myOtherImage = display.newImageRect()

```

If you call the old image again later, this is fine as the images are cached by Corona.

Secondly, you can use an image sheet:

```
display.remove(imageItem)
itemImage = nil
local myOtherImage = display.newImageRect(imageSheet, frame, width, height)

```

This allows you to pull images from an efficiently packed image sheet.

I must admit I don't fully understand what you are trying to accomplish. There is no reason you should be struggling with this and storyboard. Perhaps post a few more details with the specific problem.

As a side note, you should try and use newImageRect as this allows for scaling:

http://docs.coronalabs.com/daily/api/library/display/newImageRect.html
> 1 votes

---
Tags: lua, corona-sdk
---


# Question
Title: What tools do you use for 2D art/sprite creation?
What cheap/free tools do you use for 2D art and/or animation?

I don't really like Gimp's interface, Paint.NET is limited and GraphicsGale is sort of archaic. Cosmigo ProMotion looks like it could be good, anyone use it? Seems a bit pricey at $78/92 but of course cheaper than Photoshop.

I used to like Jasc Paint Shop Pro 7, but the newer versions Corel makes are more for photos.

2D Bones support would be handy also.

# Answer
I recently discovered Allegro Sprite Editor: http://www.aseprite.org/

It's a fairly basic pixel graphics editor with animation support, but I do prefer it over Graphics Gale as ASE has proper alpha channel support and the UI is cleaner, a bit reminiscent of Deluxe Paint. It has layer support and basic onion skinning.

It is an open source product, but downloading the source requires compilation. You can purchase the pre-compiled application. See the FAQ: if Aseprite is open source, how is it that you are selling it?
> 33 votes

# Answer
For proper 2D pixelling, I've never seen anything on PC that's a match for the Amiga DPaint series :(

The number one feature missing from most modern art software is the ability to see two different zoom levels at once (zoomed in close, and maybe a 2x-3x zoom, so see something close to 'actual pixels' at the game's target resolution)

The number two feature - it may seem a bit too picky - but I've never seen a PC mouse pointer move as smoothly as the Amiga mouse pointer. Even with a high-end 'gaming mouse' claiming silly numbers of DPI and Hz...

Just rose tinted glasses? That and that pixel art always looked sweeter on CRT screens, which we were all using back in those days?...
> 11 votes

# Answer
For pure 2D pixel art, i'd say Aseprite for the win. With v.9.1 out, so much has been added and improved.

Its open source, no catch. Constantly being updated and improved. It has: Layers support Proper alpha channel unlike GraphicsGale.. meh!, Has onion skinning. Color palette ramp. Simple and much cleaner UI. Unlimited undo options. Mini editor. Import/export sprite sheets option. Split view for more freedom and so on, and none of the "overrated" and "out of this world" stuffs you would get from this blah and this bleh.

Simple and yet reliable in every way.
> 6 votes

# Answer
GraphicsGale. It has:

* pixel zooming
* layers
* animation support
* real-time animation previews
* onion skinning
* a relatively simple interface

It's shareware, but the only restrictions are lack of support for \*.ico, \*.cur, \*.ani and animated GIFs.
> 5 votes

# Answer
Adobe Fireworks has all you need. Believe me, I invested almost a month looking for the best tool for this work.
> 5 votes

# Answer
Pro-motion by cosmigo, a Deluxe Paint clone does it for me. DPaint is more or less the oldskool pixeling standard. Nowadays, with people don't knowing about palettes and stuff it seems PhotoShop is more in vogue.
> 4 votes

# Answer
Well, personally for sprite creation I use Adobe Illustrator. It costs a lot of money, but before I got Illustrator I used Inkscape (which is completely free). You should give that a try.
> 3 votes

# Answer
The best tool I use for 2D sprites is honestly MS Paint, It does take a lot of time and patience but in the end I think its worth it.
> 2 votes

# Answer
I use Graphics Gale and Macromedia (not Adobe) Fireworks.

I have Pro Motion here, but I don't understood it properly, it is WAAAAY too complex to my taste.

The reason I use fireworks is that I can mix vector and bitmap freely, and also use photoshop plug-ins without using photoshop itself (and I dislike photoshop itself)
> 2 votes

# Answer
Even though it isn't maintained anymore, I still love Pixen for simple pixel sprite editing.
> 1 votes

# Answer
**GIMPshop** is GIMP with PhotoShop like interface.

> GIMPshop is a modification of the free/open source GNU Image Manipulation Program (GIMP), intended to replicate the feel of Adobe Photoshop. Its primary purpose is to make users of Photoshop feel comfortable using GIMP.
> 1 votes

# Answer
I know this thread is old, but I'll put my suggestion anyway.

If you want to do just 2d art(no animation) I would recommend using inkscape. Vector graphics are great for games, and the keep the art from being to complex for a small space.

If you want to do animation, and don't mind drawing each frame by hand, use Pencil. Its a great piece of software.

Finally, if you don't mind spending some money, and want to do cutout animation, buy an older version of Anime Studio Pro(at the time of writing, version 7)
> 1 votes

# Answer
The question is what you want from the software in the first place.

**If you want really good graphics** with shadows and other automatic effects then you should probably consider software for creating cartoons. For this purpose you can use *Pencil, Synfig Animation Studio, Tapptoons Linetester, eDrawings.*

**If you want to create a 2d sprite animation for 2D game** and you really want to save your time then you can consider *Flash software or the Anatomy animator.* The later is cross-platform and can work with hinged bones (skeletal animation).
> 1 votes

# Answer
I have used Photoshop for years through my work, but couldn't quite justify the cost of personal development, so I have taken up Gimp and Inkscape. I use Gimp for handrawn stuff and Inkscape for UI elements where vector graphics is a bit more predictable.

Both have quirks (especially on the Mac) which take some getting used to, but overall I am pretty happy with them.
> 0 votes

# Answer
**Photoshop Elements** (the cut-rate version of Photoshop) is better than most people think. You can find a lot of negative reviews about it, and for a professional *photographer*, it may not be good enough. It definitely has less capability, like 8-bit color instead of 16-bit color. But for a *game developer*, 8-bit color is plenty :) (That's 8 bits per RGB channel, it's also called 24-bit). And the few features that a gamedev would need which *are* missing (like alpha channel masks), can actually be added using simple workarounds.

(Note the link is for Elements 7 - it's cheaper than version 8, and 8 didn't get great reviews).
> 0 votes

---
Tags: 2d, art
---


# Question
Title: Derive a algorithm to match best position
I have pieces in my game which have stats and cost assigned to them and they can only be placed at a certain location.

Lets say I have 50 pieces.

e.g. Piece1 = 100 stats, 10 cost, Position A. Piece2 = 120 stats, 5 cost, Position B. Piece3 = 500 stats, 50 cost, Position C. Piece4 = 200 stats, 25 cost, Position A. and so on..

I have a board on which 12 pieces have to be allocated and have to remain inside the board cost. e.g. A board has A,B,C ... J,K,L positions and X Cost assigned to it.

I have to figure out a way to place best possible piece in the correct position and should remain within the cost specified by the board.

Any help would be appreciated.

# Answer
> 2 votes
Here's what I'd do:

For each position generate a list of all possible pieces that can go there. Sort them by stats. Remove any overly expensive pieces from the lists. That is ones where there's another piece with higher or equal stats and lower cost.

To start with try the best possible piece in each position. If the score is under the limit then you're done.

If the score isn't under the limit then make sure that using the cheapest possible piece in each position gets you under the score limit. If it doesn't then it's unsolvable, otherwise this is your starting point for a search. If you don't have to put a piece in all positions then start with all positions empty.

What you need to find is the combination of substitutions that gives the biggest score increase, with a cost that keeps you within the limit. Unfortunately I believe that is the knapsack problem which is NP complete, so getting a perfect answer might take a while.

However you can use a greedy algorithm to get a quick but possibly inaccurate answer by repeatedly picking the best upgrade. That is you make the change that gives the biggest increase in stats per point of cost increase (while keeping within the cost limit).

This goes wrong in some cases. For example say you have 10 points spare, and only two possible changes left that fit the budget.

1. Gain 10 stats for 2 points. 10/2 = 5 so this is the most cost effective change.
2. Gain 20 stats for 10 points. 20/10 = 2 so this isn't very cost effective.

The ideal pick is of course the second one despite the inefficiency, because if you pick the first there's nothing you can do with those last 8 points.

However it's not too expensive when the number of options is low to just try them all (there's 2^N subsets to try). When the number of options is high, hopefully you aren't close enough to the cost limit for the result to benefit significantly from a full search.

# Answer
> 0 votes
OK I believe I got this, I would start with the following.

```
For each position
  divide the total cost for board by number of positions left to fill.
  get best possible player for this position based on value above.
    return the highest stats unit with cost thats under the amount allowed
  remove cost of from total cost.
  set player chosen for this position.

```

This would mean that at every point we recheck the max cost for a player for a position, By changing the definition of best player you can manipulate how placement is done.

---
Tags: mathematics, algorithm, logic
---


title: Should I calculate in meters or pixels

text:
# Question
Title: Should I calculate in meters or pixels
In my car sim I am doing my calculations in Standard Units, except for the distance which is in pixels. Is this still correct (my guess is no) or should I use Meters ?

If I should use meters what is the best way to go about it? should I just pick a scale 10px = 1m or is there a better way to do this ?

thanks in advance.

Some additional info: I'm using Unity3D and using its physics engine.

# Answer
> 12 votes
A lot of physics engines operate at a scale of 1 unit = 1 meter. Unity isn't any different, as you can see in the manual.

> The size of the your GameObject's mesh is much more important than the mass of the Rigidbody. If you find that your Rigidbody is not behaving exactly how you expect - it moves slowly, floats, or doesn't collide correctly - consider adjusting the scale of your mesh asset. Unity's default unit scale is 1 unit = 1 meter, so the scale of your imported mesh is maintained, and applied to physics calculations. For example, a crumbling skyscraper is going to fall apart very differently than a tower made of toy blocks, so objects of different sizes should be modeled to accurate scale.

So 1 unit = 1 meter. Don't use pixels for your physic engine. Your world should be decoupled from the actual rendering output (which is in pixels)

# Answer
> 2 votes
For the best simulation accuracy, you should choose units such that typical numbers are **close to 1 in scale**; this will ensure your physics' floating-point computations are as accurate as possible. This applies to all numbers — lengths, masses, etc.

So, for games with human-scale objects like cars, 1 = 1 meter is a perfectly fine choice. On the other hand, if you were, for example, simulating a pinball machine, it would be good to scale things so that the ball's radius is 1.

---
Tags: unity, simulations, car
---


title: Simulate forces on a connected chain

text:
# Question
Title: Simulate forces on a connected chain
I'm building a 2D space game where the player uses a chain to grab on to nearby asteroids. The asteroids move along a specific path with a constant velocity.

The chain has a maximum length L and doesn't break.

The player has an update function where it checks if the chain is attached to a asteroid. If it is attached it should make sure that the distance between the player and the specific asteroid should never exceed the maximum length L.

This is what the function looks like:

```
Player.prototype.update = function() {
    // ...

    if (this.grabbed) {
        var asteroid = this.grabbedAsteroid();
        if (this.distance(asteroid) > this.chain.length) {
            // Pull player
            // ...
        } else {
            this.position += this.velocity;
        }
    }
}

```

My question is **how do I (realistically) simulate the chain pulling on the player?**

The game uses the Euler method to calculate the velocity and position of the player. The velocity and position of the asteroid are given by an arbitrary function.

# Answer
The easiest solution would be to utilize a 2D physics engine that supports chains (like Box2D), rather than rolling your own. Your question is tagged , so I suspect you might be interested in Box2dJS, a javascript implementation of Box2D. If you truly plan to roll your own 2D physics, however, I recommend you nonetheless take a look at the Box2D source code to see how chains/ropes are handled in that project.

A chain is a series of two or more connected links. The smaller and closer the links, the more flexible the chain. Box2D creates chains by treating them as a series of solid rectangles with each linked to the previous using a "revolute joint." A revolute joint attaches two objects by “pinning” them together at an anchor point which they may revolve around. Obviously, the more links in the chain, the more CPU intensive and the more rope-like the resulting behavior.

How to implement a physics engine that will simulate the behavior of revolute joints is non-trivial (hence the original suggestion to just use an existing 2D physics engine). (Here's a discussion on SE, "How do I build a 2D physics engine?") In any event, here's the revolute-joint code and their implementation of ropes to give you an idea.
> 3 votes

# Answer
There are several ways to solve this, easy and hard. The information you want to learn is tension physics.

I've drawn a diagram of the *expected* forces.

There are couple issues:

* First, we're using a rigid system while conserving the energy, assuming the asteroid has infinite mass (meaning we don't affect it by moving it).
* Second, position is always updated by velocity. (I removed your your else statement and moved the code down)

When your player reaches the edge of the chain, in this case, it is similar to a collision. I usually rotate the system so the Y axis/component is along the tension vector and the X axis/component is the remaining component.

Some Pseudocode based on yours:

```
Player.prototype.update = function()
{
    // ...

    if (this.grabbed)
    {
        var asteroid = this.grabbedAsteroid();
        if (this.distance(asteroid) > this.chain.length)
        {
            // Begin pseudocode
            var chainVector:Vector = asteroid.position - this.position;  // Vector pointing to asteroid
            var playerRelativeVector:Vector = this.velocity; // Temporary vector that we are going to rotate forward and backward.

            // align component vectors along the tangent of the tension (i.e., remove rotation and align components to axis)
            playerRelativeVector.angle -= chainVector.angle; // (2)

            // Reverse Y component because chain is 'pulling' on it
            playerRelativeVector.Y *= -1;

            // Rotate the vector back into world coordinates
            playerRelativeVector.angle += chainVector.angle; // (3)

            // Update our velocity to reflect changes to system
            this.velocity = playerRelativeVector;
        }
    }
    this.position += this.velocity;
}

```

Note, this method will not work in high-energy or precision simulations as you are calculating the position *after* you have traveled past the length of the chain. If you were to *anticipate* the position, you would be calculating the position *prior* to reaching the length of the chain. The only way to perform this precisely is to use a sweep-test and calculate the moment the player reaches the maximum length, and modify the vector at that moment. (Extremely high energy systems would require a recursive sweep test \>.\<)

Finally, I've implemented **one** recursive sweep-test physics collision system and I absolutely despise it. I would suggest using Box2D as Cameron Fredman suggested.
> 2 votes

---
Tags: physics, javascript
---


# Question
Title: Android emulator with acceleration and gyroscope simulation
Is there an Android emulator that is compatible with that can simulate acceleration and tilting of a mobile device?

# Answer
> 2 votes
Try OpenIntents SensorSimulator:

> **About the SensorSimulator**. The OpenIntents SensorSimulator lets you simulate sensor data with the mouse in real time. Moreover, you can simulate your battery level and your gps position too, using a telnet connection.
>
> NEW! Now you can record a sequence with states from a real device. Also you can use features like editing, saving, loading and playing the scenario. It currently supports accelerometer, compass, orientation, temperature, light, proximity, pressure, gravity, linear acceleration, rotation vector and gyroscope sensors, where the behavior can be customized through various settings. Here you can find new features description.

---
Tags: android, debugging, eclipse
---


# Question
Title: Problem with default 3rd person controller in Unity 4
I am new to Unity. Whenever I am importing the default 3rd person controller (construction worker) in my scene and clicking the play button, the model seems to be in the running pose.

The control keys are working properly, and I am also being able to make the character stand, walk, run and jump properly. Only problem is that it is always in the running pose - which looks very odd. I did not make any change to anything. I just imported the controller as is.

Can someone please tell me how to correct this issue?

P.S. I hope my question was clear.

# Answer
For some reason, the 3rd person controller is set to auto-play the "run" animation by default. At least in my case, and I'm guessing in yours too, since I did not change the controller in any way. To fix the issue, select the third person controller and go to its Animation component in the Inspector View (the panel to the right). It should look like this:

Next, click on "Animation", just like the picture says, and select "idle". The controller will stay idle by default now, and not run aimlessly on the spot.

LE: One more thing. It seems some users have another issue with the 3rd person controller. Apparently in Unity 4 its animation clips are not set up by default. If you see this:

Then you need to click on each MISSING animation clip and set it manually. Idle Animation should be "idle", and so forth. When selecting animations, take a look at each one's path (at the bottom of the selection window), and make sure they're coming from the 3rd person controller only!

Good luck!
> 3 votes

---
Tags: unity
---


# Question
Title: Repeat image on a fixed background, Cocos2D?
I'm quite new to Cocos2d, does anyone know how to create a background that would be one fixed screen (no scrolling), with a small image just repeated to the whole size of the screen - depending on device?

The best way I can explain the look I'm after is something similar to repeating a small image for a website background.

Thank you in advance for any help :)

# Answer
> 4 votes
Since cocos2d is OpenGL based (sprites are just textured quads), you can create one large quad and modify the UV coordinates accordingly.

You don't have to mess with the UV coordinates yourself, cocos2d has some helper methods for that. In order to have an image repeat over the whole screen, you can do something like this:

```
// get the screen size
CGSize screenSize = [[CCDirector sharedDirector] winSize];

// create a sprite from file that will cover the whole screen
CCSprite* bg = [CCSprite spriteWithFile:@"image.png"
    rect:CGRectMake(0, 0, screenSize.width, screenSize.height)];

// set texture parameters to repeat
ccTexParams params = {GL_LINEAR,GL_LINEAR,GL_REPEAT,GL_REPEAT};
[bg.texture setTexParameters:&params];

// position the quad at the center of the screen
[bg setPosition:ccp(screenSize.width * 0.5f, screenSize.height * 0.5f)];

```

Now you should have a sprite `bg` that covers the whole screen with the repeated texture from `"image.png"`.

# Answer
> 0 votes
Something along the lines of this...

NOTE: I have minimal knowledge of cocos2d/objective c

This is a nested for loop, If you would like to access data from each image at a later stage i'd suggest adding each tile to an array inside the nested for loop :) Hope this helps

```
    CGSize size = [[CCDirector sharedDirector] winSize];
    int TILE_SIZE = 57

    for (int y = 0; y < (size.height / TILE_SIZE); y++) {
        for (int x = 0; x < (size.width / TILE_SIZE); x++) {
            CCSprite *tile = [CCSprite spriteWithFile:@"Icon.png"];
            [tile setAnchorPoint:ccp(0, 0)];
            [tile setPosition:ccp(x * TILE_SIZE, y * TILE_SIZE)];
            [self addChild:tile];
        }
    }

```

The "57" in the set position method is the width and height of the image respectively.

**If you want the images to fit perfectly in the screen then they will have to be resized accordingly**

---
Tags: ios, cocos2d
---


# Question
Title: How can I change the acceleration of an object to arrive at a particular time?
I'm trying to write some code to change an acceleration factor so a ball will arrive at a destination in a desired time.

The problem is I don't know time (t) but I do know I want it to arrive at (t - x) where I can feed the value of x.

The ball has an initial velocity so the equations of motion I imagine to use is:

s = ut + 0.5at^2

I have the distance (s), the starting velocity (u) and the current acceleration (a).

Ultimately, I want to be able to get a new acceleration value (a) that will make the ball arrive, for example, 100ms later than it's intention with the current (a) value.

Any pointers, much appreciated! (I'm using javascript).

# Answer
> 11 votes
I'm assuming you want only **1-dimensional movement**; movement in a straight line.

As you say, `s = ut + a*t*t/2`, where `u` is initial velocity, `a` is acceleration and `t` is time. Rearranging for `a` gives `a = 2*(s - u*t) / (t*t)`.

To arrive at a different time, just substitute a different value for `t`. To get a feel for how it works, you could try it on Wolfram Alpha.

Note that if your physics are using approximating reality by running a calculation every step rather than actually following a differential equation curve (i.e. Euler integration), this won't *quite* match up. (Though with small and frequent steps, it's really close.)

---

**Edit**: So how do you calculate how long the ball takes to get there *in the first place*? It's a little harder, since `t` is quadratic, but it's still high-school maths.

Here's a sketch:

Now we could substitute the red equation for `t0` into that last equation for `a`, but it would get messy.

I'd recommend just working it out in two steps like that.

To reiterate:

1. Use your known values to solve `s = u*t0 + a*t0*t0*/2` for `t0` to get the time the ball takes to get to its destination.
2. Rearrange `s = u*t + a*t*t*/2` to solve for the new acceleration value `a`.
3. Substitute `t0 + desiredDelay` for `t`.
4. Solve for `a`.

# Answer
> 4 votes
Anko's answer is excellent, but I'd like to summarize it a bit and fill in some missing details.

As you correctly note, the formula for motion under constant acceleration is:

> s = vt + ½at2

where `s` is the distance the object moves during a time interval of length `t`, `v` is the initial velocity of the object at the beginning of the interval, and `a` is the acceleration. As written, this formula gives `s` as a function of `v`, `t` and `a`, but we can solve it for `a` as a function of `s`, `v` and `t`:

> ½at2 = s − vt
>
> a = 2(s − vt) / t2

Solving for `t` as a function of `s`, `v` and `a` is also possible, but requires the quadratic formula:

> ½at2 \+ vt - s = 0
>
> t = −v/a ± sqrt(v2 \+ 2as) / a

Note that the formula gives us two solutions, depending on the sign in front of the `sqrt`; we don't want negative solutions, so we should choose the plus sign if `a` is positive and the minus sign if `a` is negative, or, in other words:

> t = −v/a + sqrt(v2 \+ 2as) / abs(a)

(This formula will always give the larger of the two solutions, if there are any. It's possible for even this solution to be negative, if we're both moving and accelerating away from the target and will thus never meet it again with the current acceleration. It's also possible to have two positive solutions, if we're going to pass the target once in each direction, or to have no real-valued solutions at all, if our trajectory has never passed the target and never will; e.g. the trajectory is that of a thrown rock, and the target is the moon. In that last case, the input to the `sqrt` function will be negative.)

Now we can just use this solution to calculate the expected arrival time, adjust it any way we like, and then use the earlier solution for `a` above to calculate the acceleration needed to arrive at that time.

---

Now, the remaining problem is that the formula above is for exact Newtonian mechanics. If your game is using a poor physics simulation, it may deviate from the exact motion, in which case the simulated path of your object may not match the predictions of this formula.

The best solution is to use a better physics simulation.

In particular, to get accurate trajectories under constant acceleration, you should apply the first formula above *on each time step* to compute new object positions, like this:

> x' = x + vΔt + ½aΔt2
> v' = v + aΔt

Here, `x` and `v` are the initial position and velocity of the object before the timestep, `x'` and `v'` are the *new* position and velocity of the object after the time step, `Δt` is the length of the time step and `a` is the acceleration.

As long as `a` is constant, this formula gives exact results (up to the limits of numerical accuracy, anyway). If `a` can vary, you can get even better results using the velocity Verlet method described in the linked post:

> a = a(x, v, t)
> x' = x + vΔt + ½aΔt2
> a' = a(x', v + aΔt, t + Δt)
> v' = v + ½(a + a')Δt

# Answer
> 0 votes
If you just want to interpolate some variable between 2 values during some time, I recommend to use some tweening library, e.g. Tweener. It contains linear interpolation, quadratic, cubic, sine etc.

BTW whenever you want to change position by editing velocity or acceleration, just compute the derivative of movement equation and solve it. You can copy movement equations from Tweener library.

---
Tags: mathematics, physics, javascript
---


# Question
Title: Get intersected volume of two planes in 3D
I'm working on AABB - AABB collision response and I'm having trouble figuring one part out. My situation is as follows (see image).

I have a player AABB (blue) and an object which collides (brown). I've drawn a few faces for both AABB's. The player moves towards the cube and collides with two planes (colliding planes have their normal's drawn). These normals will be returned in the code in the 'normals' vector. I then check the opposing planes and try to get the volume of the intersected plane (right side of image).

I based my face detection algorithm on the following question : AABB - AABB Collision, which face do I hit?

**The Two AABB's colliding** (blue is Player AABB and brown is object)

If I have multiple normals returned (which happens when two faces collide) I want to calculate the highest intersected volume between the collided faces and take that normal as the normal to base my collision response on (right side of image). It works for some faces but for the other half it doesn't work and I assume this has to do with change of vertex order which make my substractions pointless in some cases.

Is there some general way to calculate the volume of two intersecting planes in 3D that helps me resolve my response?

Code attempt for calculating highest volume between two (not working as it should):

```
functionThatDoesCollisionResponse
{
    [...]
    // Calculate size differences first
    for(int i = 0; i < normals.size(); i++) // Normals is vector filled with all intersected plane normals.
    {
        Vector oppNormal = normals[i].Negative();
        Plane pFace = this->GetPlaneFromNormal(player, oppNormal); // Returns plane with specified normal
        Plane oFace = this->GetPlaneFromNormal(object, normals[i]);
        sizeDifs.push_back(this->CalculateSizeDifference(pFace, oFace)); // Pushes differences of size in Vector for later calculation
    }

    // Don't take average but take highest intersected volume plane
    GLfloat min = 9999999.99f;
    Vector bestNormal;
    for(int i = 0; i < sizeDifs.size(); i++)
    {
        GLfloat opp = sizeDifs[i].x * sizeDifs[i].y * sizeDifs[i].z;
        if(opp < min)
        {
            min = opp;
            bestNormal = normals[i];
        }
    }
    [...]
}

Vector CollisionEngine::CalculateSizeDifference(Plane p1, Plane p2)
{
    GLfloat xDif = p1.topLeft.x - p2.topLeft.x;
    GLfloat yDif = p1.topLeft.y - p2.bottomLeft.y;
    GLfloat zDif = p1.topLeft.z - p2.bottomRight.z;
    return Vector(abs(xDif), abs(yDif), abs(zDif));
}

```

# Answer
1. The intersection between two planes is a line...
2. Work with bounding boxes not with planes...

don't generate a plane from a normal, generate the bounding box and its corners... this way you will know what are the front, back, right, left, top and bottom sides, and the code is easier...

if there are true AABB, you only need two points that keep min and max coordinates... and then knowing the intersection is much easier...
> 2 votes

---
Tags: c++, 3d, mathematics, collision-resolution, aabb
---


title: Problems moving a rectangle in Pygame

text:
# Question
Title: Problems moving a rectangle in Pygame
I'm making a game in Pygame and I want to be able to target enemy unit. I made it so when I click on them a variable "targeted" becomes true, and stays true until I click somewhere else on the screen. I also want targeted units to have a small green circle around them, so I made it in GEDIT. I have made a function that draws everything on the screen (the background, the player, objects, etc) and in the part where it draws the units it checks if the variable "targeted" is true and if it is it should move that little green circle over the enemy units.

here is the code that does that:

```
screen.blit(enemy_unit.pic, enemy_unit.rect) #draw the unit

if enemy_unit.targeted == True: #if the unit has been targeted then draw a circle over it
    target_rect.move_ip(enemy_unit.pos)  #move the circle to the unit
    target_rect.fit(enemy_unit.rect)     #there are some bigger units and some smaller ones, so we have to "scale" the circle
    screen.blit(target_pic, target_rect) #actually draw the circle

```

This doesn't work, when I target the unit the circle just appears for a 1/5 of second next (not on, but just next) to the unit and then disappears. I am sure that I am keeping a good track of "enemy\_unit.pos" because I tested it (I added a piece of code that would print one units position and mouse's position every time i clicked the mouse and when i was near him the numbers were same).

If you could give me a hint about what I'm doing wrong. I think its in move\_ip function, but I tried just move and it didn't work either (the circle didn't even show at all)!

# Answer
```
 elif event.type == MOUSEBUTTONDOWN and event.button == 1 and pressed == False:
      pressed = True
      for enemie in lista_neprijatelja:
           if enemie.rect.collidepoint(pygame.mouse.get_pos()):
                enemie.targeted = True
           else:
                enemie.targeted = False

 elif event.type == MOUSEBUTTONUP and event.button == 1 and pressed == True:
      pressed = False

```

I am sure that this works as it should - I tested it.
> 2 votes

# Answer
in each game iteration you should check - if user clicked on other unit or surface, if yes - change selected unit or remove selection from currently selected

It will look something like this: somewhere in main loop:

```
    user_input.get_user_input() # grab user mouse input
    game.screen.event_handling(user_input)  # see below:

```

game.screen.event\_handling function:

```
def event_handling(self,event_handler_object):
    for unit in self.unit_list:
        unit.update_state(event_handler_object)

```

In unit.update\_state(event\_handler\_object) function you should check any mouse events like MOUSEMOTION, MOUSEBUTTONDOWN, MOUSEBUTTONUP. Also you should store last mouse event to compare current event, for example - usel clicks some unit, your actions:

1 - wait mouse event

2 - check if there any unit under this coordinates, if yes:

2.1 - set unit status "selected"

2.2 - set last\_event = {"event":"click,"pos":pygame.mouse.get\_pos()}

3 - get next (current mouse event)

4 - check if event is MOUSEBUTTONDOWN:

IF event is MOUSEBUTTONDOWN then:

4.1 - goto #2

sorry, I'm little drunk in this moment, but logick will be like above. I you have any questions - tomorrow I will can share my code of the same mynctionality
> 0 votes

---
Tags: python, pygame
---


title: java app goes too slow in android os

text:
# Question
Title: java app goes too slow in android os
The problem is that my java app contains too many animated sprites and it runs very slowly on android system.

Does the usage of .gif animation instead of sprite animation will improve the speed?
I really don't know which animation technique consume less CPU time.

# Answer
> 1 votes
Whether you are able to render .gifs acceptable for your needs (frame timing, alpha channel) or not? It all depends on implementation. But the resulting app's size will not be reduced, if the device's memory is a considerable bottleneck.

---
Tags: java, android, animation, sprites
---


# Question
Title: Free animated character models for my first Unity game
I am creating my first game in Unity for my intra-college game development competition. A hack and slash type of game. It's about a warrior who is escaping from a prison. Setting is medieval times. Thing is, I am looking for 3 free (low poly) animated character models which are appropriate for this game. 1. The hero (has a sword, with optional shield) 2. Basic enemy guard (with sword/ hammer/ other melee weapon, no shields) 3. Boss (with melee weapon) I searched for the above over the last couple of days, but couldn't find them.

My modeling skills are not such that I can create my own character models. However I have managed to create the game levels. Now I am looking for some help with the character models.

Can anyone please link me to the appropriate free models?

Last date of game submission is March 8. So I need the models urgently. Please help.

P.S. The game is slightly inspired by Prince of Persia: Warrior Within

# Answer
> 2 votes
To my knowledge I don't really know of any sites that would give 3d models already animated for free, but you might be able to find some for a low price (if you're willing to spend a bit):

first look on the, https://www.assetstore.unity3d.com/

then I would go to, http://www.turbosquid.com/

lastly (but still good), http://www.3drt.com/3dm/3dm.htm

And if you still can't find any I would have recommend contacting someone or a site and ask to use some animated models for educational use (not commercial). But since this is time sensitive I think buying them or making them (which would take a lot of time) are the only options.

Edit: I found this haven't had time to go through it properly but it may help in your search, http://www.hongkiat.com/blog/60-excellent-free-3d-model-websites/

---
Tags: unity
---


title: How would I make an air hockey AI?

text:
# Question
Title: How would I make an air hockey AI?
I am making an air hockey game for Android using AndEngine and its Box2D extension.

How would I make an AI for an air hockey game? For it to work the AI would not only need to move its paddle side to side to defend but also move forward for an attack. What kind of code would I need to implement this?

# Answer
The mechanics for air hockey are not particularly deep, so it wouldn't take much to generate reasonable behavior. Think of the movement of the paddle as comprised of several different types of movement:

* Wander - to some extent people simply move the paddle around, both left and right and forward and back to keep the enemy guessing.
* Defend - blocking the goal is important (and more important than not blocking the goal) but you want the left right wandering to "lure" the opponent into trying to take a shot.
* Attack - attempt to score a goal.

So first you need some code that allows for performing the above three behaviors. You'll need code that can take a shot, etc. One of the tricks here is going to be generating the "desired" vector of the paddle that would create a goal when it hits the puck (assuming it isn't blocked). You're going to have to anticipate the position of the puck based on its velocity and anticipate a location far enough out in time that the appropriate velocity of the paddle can be accomplished. Note that this "attack" pattern can be tweaked so it's a defense pattern. I.e., think of the "desired" vector of the paddle being a resulting velocity from its interaction with the puck such that the puck goes *anywhere* but the AI's own goal. (So in fact, the "Defend" behavior above might be subdivided into two: (1) knock the puck away from its velocity toward the goal; (2) just get in the way of the puck and the goal.) I'd probably start with implementing #2 as it's the most simple, but will still force you to deal with anticipating the results of the puck's velocity.

Once you have your behaviors, rather than have a single one of them control the paddle at any given time, try having all three control the paddle simultaneously, but with different relative weights. So you might say at one moment, the movement is 60% attack, 20% wander, and 20% defend. Average together those movement vectors to determine the paddle's movement.

Next, you'll want to play with the relative weights at different times. The question is, under what circumstances when playing air-hockey do you lean more toward one of the other tactics than another? When somebody inadvertently takes a very slow shot at you, that would seem to be an opportunity for a very aggressive attack. On the other hand, when the puck is coming in fast and toward the goal, that would be a time when you'd have to play as defensively as possible. When the puck is on the other side of the table (the enemy's side), that's a time when "wandering behavior" is more appropriate. Etc. So you'll want to look at the puck to influence the weights.

You might also want to take into consideration the enemy paddle location to determine the weights. (I.e., if the player paddle is far away from defending its own goal, you might want that to increase the % of attack.)

Next, add some error. The computer shouldn't play perfectly, it should slip up a little to make it "feel" more natural. For example, you're going to need to have the AI anticipate the puck location (both for attack and defense), but add the wiggle room to have it anticipate a little early or late.

Finally, for brownie points, you could implement some adaptive behavior. This is probably over-the-top for an airhockey game, but what I mean is, you can have the AI tweak the relative weights of its behaviors based on its past success or failure. When playing a game, rather than have forced percentage weights based on the above circumstances, tweak them a little each game randomly. Then look at the results: was the AI winning more when it played with a particular weighting distribution? If so, use that as the new default and start tweak-randomizing from there.
> 11 votes

---
Tags: android, box2d, ai, andengine
---


# Question
Title: Game library for 2D animation JS browsergame
I am developing a 2D multiplayer online browsergame.

On the backend I have set up a Node.js server. Everything works perfectly.

On the frontend I will use jQuery and several libs for collision etc. so far.

I will not use canvas, Audio nor massive player numbers.

My question is, what is the **best library for 2D animations**?

Libs I know: craftyjs

"Animation" means: advanced moving/calculating of elements, keyboard movement, if possible collision detection

# Answer
Since you don't want to use Canvas I would look into Spritely or gameQuery. Note that both are plugins for jquery, which you are already using.
> 1 votes

# Answer
As an alternative to CraftyJS, consider these possibilities:

Which is "best" is going to take us into a discussion that's outside the scope of GameDev, as well as very subjective and very much dependent on your needs. But the websites for these should give you an idea of their relative features.
> 0 votes

---
Tags: 2d, animation, browser-based-games, node.js, jquery
---


title: HLSL - Creating Shadows in 2D

text:
# Question
Title: HLSL - Creating Shadows in 2D
The way that I create shadows is by the following technique: http://www.catalinzima.com/2010/07/my-technique-for-the-shader-based-dynamic-2d-shadows/

But I have questions to HLSL. The way that I currently do it is, I have a black and white image, where Black means 'object', and white means 'nothing'. I then distort the image like in the tutorial. I do this with a pixel shader, but instead of rendering to the screen, I render to a texture, back to my application. I then take this, and create the shadows, and then send it back to the graphics card to undo the distortion, after the shadow has been added - this comes back and I have a stencil of shadow. I can put this ontop of the original image and send them back to the graphics card, which then puts them on the screen.

To me this is alot of back and forth. Is there a way i can avoid this?

The problem that I am having is that I need to basically go through all positions in the texture 3 times, and use the new new texture every time instead of the orginal one. I tried to read up on Passes, but i don't think that i am heading in the right direction there.

Help?

# Answer
> 2 votes
I've studied Catalin's method for quite a while. The problem with this method is that it's pixel perfect. That requires a great deal of work in the pixel shader to function, although with great effect.

A much faster way of creating shadows is via the vertex shader. I tried Krypton and am thinking of adding shadow meshes to my content just to use it. Video

# Answer
> 0 votes
The best you'll be able to do is to have two lights.

You'll notice in one of the later steps, the distortion of horizontal position is stored in the red channel and vertical position is stored in the green channel. The blue and alpha channels are currently unused, meaning that you could essentially perform this shader on two light sources.

It's a really complicated and expensive shader, so I don't think you'll be able to cut out more than maybe one step.

---
Tags: xna, 2d, hlsl, gpu
---


# Question
Title: How does the Path of Exile ItemRenderer determine the items' rarity?
This question is really specific to Path of Exile and their forum.

Basically, they render the items from a json object.

```
require(["PoE/Item/DeferredItemRenderer"], function(R) { (new R(JSON)) })
```

And the json of an item is of the form:

```
      {
         "verified":true,
         "w":1,
         "h":1,
         "icon":"http:\/\/webcdn.pathofexile.com\/image\/Art\/2DItems\/Rings\/Ring5.png?v=d645f9adfc012c52674c94d16b4292b2",
         "support":true,
         "league":"Default",
         "sockets":[

         ],
         "name":"Honour Grip",
         "typeLine":"Topaz Ring",
         "identified":true,
         "requirements":[
            {
               "name":"Level",
               "values":[
                  [
                     "41",
                     0
                  ]
               ],
               "displayMode":0
            }
         ],
         "implicitMods":[
            "+22% to Lightning Resistance"
         ],
         "explicitMods":[
            "Adds 4-48 Lightning Damage",
            "+8 to Evasion Rating",
            "+70 to maximum Life",
            "+35% to Cold Resistance"
         ],
         "frameType":2,
         "socketedItems":[

         ]
      }

```

I don't see the rarity of the item anywhere... How do you think they determine it? They could count the mods, but what if the object is not identified?

# Answer
It's the frameType property. I've tested this and changing it will change the colouring of the display box.

The possible values are:

* **0** Normal Item
* **1** Magic Item
* **2** Rare Item
* **3** Unique Item
* **4** Gem
* **5** Currency
* **6** Quest Item
> 3 votes

---
Tags: data-driven
---


# Question
Title: Using IGameComponent and related interfaces in MonoGame
I am trying to port a XNA project to MonoGame which involves a DLL game library that I created. This library uses the IGameComponent, IUpdateable and IDrawable interfaces to load one of my library classes as a GameComponent.

The compiler gives errors related to these interfaces, saying, for example: *The type 'Microsoft.Xna.Framework.IUpdateable' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.Xna.Framework.Game'...*

This would require me to add Microsoft.Xna.Framework.Game to my reference list, which defeats the point of porting to MonoGame. Is there any way these interfaces can be made compatible with MonoGame

# Answer
You'll need to recompile your DLL game library after changing all the XNA references to MonoGame references.

MonoGame redefines the interfaces under the same namespace but in a different assembly. It makes things easier to port once you understand whats going on, but can make errors like this slightly confusing.
> 2 votes

---
Tags: xna, monogame, porting
---


# Question
Title: How to get an affect for balloon bursting in XNA?
I am a noob in XNA. I want to create an effect which shows a balloon bursting?

Any pointers would be highly appreciated.

# Answer
> 4 votes
Just have a one-frame image showing a bursting balloon. It doesn't even have to be great quality. See this example:

Animators can get away with a lot when it's something that appears very briefly. You'd be surprised how well this works.

---
Tags: xna, xna-4.0
---


# Question
Title: Rotation of Rectangle along Y-axis transformed to parallelogram
After the rotation of a rectangular view along the Y-axis, about its center, transformed into parallelogram, how do I get the rotated parallelogram coordinates?

By Y-axis, I mean perpendicular to the device screen.

Rotated rectangle:

Original rectangle:

Not using the openGl, ViewProperty animator is used!

# Answer
> 2 votes
First of all the resulting shape is not a parallelogram but a trapezoid. From what you write I gather that you are using the fixed-function pipeline rather than the programmable pipeline (which makes the solution really quite obvious). Basically what you need to do is perform the processing of the vertices again the same way as OpenGL does. This is the only way I could think of. If you now a better one let me now. You can use glGet to retrieve your modelview and your projection matrices and than apply them to your coordinate vector. This would leave you with the coordinates in clip space. You can than perform the division by W to get normalized device coordinates. Than perform the viewport transform to end up with window coordinates. I guess these are the coordinates you want. Alternatively you could also loop through the framebuffer and scan for colour changes. This would be a far less efficient way.

This explains nicely on how to multiply a matrix and a vector: http://www.facstaff.bucknell.edu/mastascu/elessonsHTML/Circuit/MatVecMultiply.htm

This gives a nice explanation of the OpenGL pipeline: http://www.songho.ca/opengl/gl\_transform.html

EDIT: This appears to be exactly what the function gluProject does.

---
Tags: android, rotation, geometry, transformation
---


# Question
Title: xna creating game stage management contrls
I am under planning stage of my game where I am creating controls for my game. I have create below control for stages but have no idea how this we can achieve in xna.

Please also help me with your views regarding how to load, play multiple stages and persist score for each stage in game using xna. What we normally used to do is just put everything in infinite loop but here I want more intelligence in game, as one stage over it should go back to menu. Example can be something like angry bird stages.

# Answer
> 1 votes
You're starting point is to look at the Game State Management tutorial provided by Microsoft here: http://xbox.create.msdn.com/en-US/education/catalog/sample/game\_state\_management

In that example, you *can* create and use global variables in the ScreenManager class for score etc. This would provide a simple method of persisting across the various states.

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


# Question
Title: Are javascript MVC model implementations too slow for games?
I wanted to implement a game in javascript with an MVC design pattern, with each entity's state stored in a model.

So for example,

In an update loop we iterate over all models and apply the velocity attribute to the position attribute of the model. A view associated with each entity/model would then receive a position changed event, and update the representation of the entity. This would happen independently of the views render method being called in a requestAnimationFrame callback.

What I found though, through a possibly naive implementation, is that setting attributes of a model is simply too slow. As much as I prefer the architecture of this code, the framerate was significantly lower.

Should I give up on using MVC for frequently updated attributes like position?

Below, I've included some code to test aspects of setting attributes of an object. The most minimal model-like behaviour, in which an attribute is set only when the new value differs from the current, and a "changed" update event is triggered, is about 10x slower than just setting attributes directly.

Output:

> \> test(1000, 100, 10)
>
> object\[key\]: 163 ms
>
> object\[key\] if changed: 172 ms
>
> object\[key\] if changed & emit backbone event: 953 ms
>
> Backbone.Model: 4043 ms
>
> eventsBackboneCount: 100000

```
var test = function(creations, iterations, keyCount){
  var eventsBackbone = _.extend({}, Backbone.Events);
  var eventsBackboneCount = 0;
  eventsBackbone.on('all', function(){
    eventsBackboneCount = eventsBackboneCount + 1;
  });

  var looper = function(label, create, set){
    var start = (new Date()).getTime();

    var data = {};

    for(var i = 0; i < creations; i++){
      data[i] = create(i);
    }

    for(var j = 0; j < iterations; j++){
      for(var i = 0; i < creations; i++){
        var key = ''+(j % keyCount);
        set(data[i], key, Math.random());
      }
    }

    var end = (new Date()).getTime();

    console.log(''+label+': '+(end - start)+' ms');

    return data;
  };

  looper(
    'object[key]',
    function(id){
      return {};
    },
    function(datum, key, value){
      datum[key] = value;
    }
    );

  looper(
    'object[key] if changed',
    function(id){
      return {};
    },
    function(datum, key, value){
      if(datum[key] !== value){
        datum[key] = value;
     }
    }
    );

  looper(
    'object[key] if changed & emit backbone event',
    function(id){
      return {id:id};
    },
    function(datum, key, value){
      if(datum[key] !== value){
        datum[key] = value;
        eventsBackbone.trigger('changed:'+datum.id, datum, key);
     }
    }
    );

  looper(
    'Backbone.Model',
    function(id){
      return new Backbone.Model({});
    },
    function(datum, key, value){
      datum.set(key, value);
    }
    );

  console.log('eventsBackboneCount: '+eventsBackboneCount);
};

```

# Answer
> 1 votes
**TL;DR**: Typically, yes. But maybe not.

Javascript MVC frameworks are primarily for making it simpler to cause an update in a model to trigger a UI refresh or a save call to the data store, or similar tasks.

From playing around with them, it looks like MVC architecutres (ie: Backbone and co.) are really just prebuild object prototypes with some informal protocols for updating data. The concepts and features are powerful when you're making basic GUI pages, but are less impressive when looking at them from a gamedev angle.

In a game, you generally want to go through as few significant layers of indirection as possible. Just give yourself a top level object-namespace type thing that contains all your game variables and access them directly. Getting some object to notify some bit of code that it has changed isn't terribly useful if you're polling the state of that object every update frame anyway. Those `if(datum[key] !== value){` blocks aren't free.

Choose which specific properties of an object for which it's *absolutely* necessary that events happen (instead of just polling and keeping a "previousVal" var for each specific bit of code that needs it), and limit your events to only update on that set. You can even make a reusable mechanism like Backbone's attributes so long as you keep an eye on how often you're triggering events.

It's silly to send `changed` events and check if the value is already not equal for position changing, because you're going to redraw most of these things every frame anyway, so just keep writing it into memory, even if you write "position.x = 142" thousands of times (although maybe at that point you can have a collection of "static" objects ;) ).

Libs like underscoreJS are probably a good thing to take advantage of, since it's primarily about providing functions that make data manipulation easier and doesn't appear to make assumptions about your architecture.

And you may even be able to keep using Backbone as infrastructure for just exclusively emitting `changed` events for those properties that *really* need it or would **really** make your life simpler if you had them.

But don't go to the other extreme and refuse to ever abstract around an object property.

# Answer
> 0 votes
JS MVC frameworks was not designed for game development, they add a lot of syntatic sugar which leads to perfomance problems, that's why it's not the best solution to use them for this kind of application. But, actually, it depends on what kind of game are you developing, in some cases it's fine.

Sorry for my english.

---
Tags: javascript, mvc
---


title: Fluid Particle Grid

text:
# Question
Title: Fluid Particle Grid
So recently I have been looking at some fluid simulation techniques, specifically Smoothed Particle Hydrodynamics. One of the key components is a grid to avoid O(n^2) searches. I have been having some trouble implement a grid of my own.

I have been able to kind of divide the particles into a grid, and then query a particle ID to get a list of neighbors. Great! However upon further analysis I was receiving list much bigger than I expected, and sometimes exceeding the total number of particles in the simulation, sometimes there would be 140 in a single cell

I have been able to determine that the problem maybe in the UpdateGrid() method, as it seems to be allocating 24,000 particles instead 400. I am really quite lost. Any help would be appreciated.

```
#include "FluidScene.h"

CFluidScene::CFluidScene(void)
{
    GRAVITY = Vector2D(0, -2);
    EPSILON = pow(10, -6)/ 2;

    CELL_SPACE = 0.15;
}

CFluidScene::~CFluidScene(void)
{
}

void CFluidScene::Start()
{
    std::cout << "fluid scene loading...\n";

    Width = 9;
    Height = 12;

    //make the grid... here we go
    int gridx = Width / CELL_SPACE;
    int gridy = Height / CELL_SPACE;
    Grid = new std::vector<int>[gridx, gridy];

    //spawn some particles
    for (int y = 1; y < 21; y++)
    {
        for (int x = 1; x < 21; x++)
        {
            Positions.push_back(Vector2D((float)x * CELL_SPACE, ((float)y * CELL_SPACE + Height / 1.5)));
            Velocities.push_back(Vector2D::Zero());
            Forces.push_back(Vector2D::Zero());
        }
    }

    CFluidRenderer::Start(&Positions);
    CScene::Start();
}

void CFluidScene::Update(float dTime)
{
    Solve(dTime);
// test getting the neighbours
    std::vector<int> r = GetNeighbours(19);
    if (r.size() > 0)
        std::cout << Positions[GetNeighbours(19)[0]].y << "\n";

    std::cout << r.size() << std::endl;;
    //system("cls");
    CScene::Update(dTime);
}

void CFluidScene::Solve(float dTime)
{
    UpdateGrid();
    CalculateForces();
    UpdateParticles(dTime);
}

void CFluidScene::CalculateForces()
{
    for (int i = 0; i < Positions.size(); i++)
    {
        Forces[i] += GRAVITY;
    }
}

void CFluidScene::UpdateParticles(float dTime)
{
    for (int i = 0; i < Positions.size(); i++)
    {
        Velocities[i] += Forces[i];
        Forces[i] = Vector2D::Zero();
        Positions[i] += Velocities[i] * (dTime * dTime) * 0.99;
        BoundaryCollisions(Positions[i]);
    }
}

void CFluidScene::BoundaryCollisions(Vector2D &pos)
{
    if (pos.x < 0)
    {
        pos.x = 0 + EPSILON;
    }
    if (pos.x > Width)
    {
        pos.x = Width - EPSILON;
    }
    if (pos.y < 0)
    {
        pos.y = 0 + EPSILON;
    }
    if (pos.y > Height)
    {
        pos.y = Height - EPSILON;
    }
}

void CFluidScene::UpdateGrid()
{
    int w = Width / CELL_SPACE;
    int h = Height / CELL_SPACE;
    Grid = new std::vector<int>[w, h];
    int i;
    for (i = 0; i < Positions.size(); i++)
    {
        int gridx = (int)Positions[i].x / CELL_SPACE;
        int gridy = (int)Positions[i].y / CELL_SPACE;
        Grid[gridx, gridy].push_back(i);
    }
}

std::vector<int> CFluidScene::GetNeighbours(int i)
{
    std::vector<int> ret;

    int gridx = (int)Positions[i].x / CELL_SPACE;
    int gridy = (int)Positions[i].y / CELL_SPACE;

    int ax, ay;

    for (int y = -1; y < 2; y++)
    {
        for (int x = -1; x < 2; x++)
        {
            ax = gridx + x;
            if (ax < 0)
                ax = 0;
            ay = gridy + y;
            if (ay < 0)
                ay = 0;
            int j;
            for (j = 0; j < Grid[ax, ay].size(); j++)
            {
                ret.push_back(Grid[ax, ay][j]);
            }
        }
    }

    return ret;
}

```

# Answer
You allocate Grid like this: `Grid = new std::vector<int>[gridx, gridy];`

C++ is not C#, this does not quite what you expect.

`gridx, gridy` is evaluated (thanks to the comma operator) to just `gridy`, so you are allocating an array of `gridy` `std::vector<int>`s.

The same thing happens when you try to access `Grid[x,y]`, you are actually accessing `Grid[y]`.

Also, you are `new`ing a bunch of vectors on each update, without deleting the old ones anywhere, so you are leaking memory, too. It's not really necessary to allocate the grid again and again, or at all.

You could just use something like `std::vector<std::vector<std::vector<int>>>` for your grid, and access grid cells like this: `Grid[x][y]`

You can clear the stored ints like this:

```
for (int x = 0; x < gridx; ++x)
{
    for (int y = 0; y < gridy; ++y)
    {
        Grid[x][y].clear();
    }
}

```
> 6 votes

---
Tags: c++, physics, grid
---


# Question
Title: Collision Resolution: How to avoid Interpenetration/Tunneling Caused by Prior Collision Handling?
My game processes world collisions followed by entity collisions. The problem here is that entities can break through walls the next frame when world checks are run again as a result of the prior collision resolution. For example:

1. Entity1 is up against a wall and pushing against it
2. Entity2 runs into Entity1, collision detection resolves Entity1 inside the wall.
3. World collisions push Entity1 onto the other side of the wall.

What happens is that Entity2 pushes Entity1 into the wall far enough that when the world collision detection attempts to find the shortest distance out of the wall, that position happens to be on the other side.

# Answer
> 1 votes
The place to fix it is in step 2.

If Entity2 runs into Entity1, Entity1 gets moved, but **only** if the resulting location is not a new collision. In that case you'll have to move Entity2 back to it's original position or some other custom solution (for example: try moving Entity1 to a different direction that doesn't cause a collision).

---
Tags: c++, collision-detection, algorithm, collision-resolution, entity
---


# Question
Title: How to set multiple times, in a single spritebatch, the same pixel shader parameter
I make a test with Effect class in XNA and I want to set multiple times the same parameters (MyParameter in below code).

My code is :

```
[...]
//In Engine class
Effect ShaderEffect = GameEngine.Instance.Content.Load<Effect>(@"shaders\test");

spriteBatch.Begin(
    SpriteSortMode.Deferred,
    BlendState.AlphaBlend,
    SamplerState.PointWrap,
    DepthStencilState.Default,
    RasterizerState.CullNone,
    ShaderEffect);

[...]

//in drawable class
foreach(//big loop) {
     ShaderEffect.Parameters["MyParameter"].SetValue(//random vector4);
     spriteBatch.Draw(
            SpriteSheet,
            ScreenRect,
            sprite_to_draw.Rectangle,
            color,
            rotation,
            Scene.getInstance().Camera.Position,
            sprite_to_draw.SpriteEffect,
            layer
     );
}

[...]

//In Engine class
spriteBatch.End();
[...]

```

But on my screen it look like the Parameter "MyParameter" is not overwrite.

So can I overwrite it and If yes do you know how ?

Thanks

# Answer
I'm afraid there is not an **easy** solution to this problem, because you can not add extra information to the vertices generated by `SpriteBatch`.

Like Blau said, you can change the `SpriteBatch` to `Immediate` mode, or call `Begin()` and `End()` every time you change the parameter, but you will get a ton of draw calls and won't be batching anything anymore. I can think of two additional solutions:

1) `SpriteBatch.Draw` takes a `color` parameter and stores it inside each vertex of the quads it generates. You can then get this value back in your custom shaders. If you do not need to use the default color tinting, and your only parameter is a `float4` like in your example, you *could* hijack the `color` parameter for your needs, and override the default pixel shader so that it does not tint the sprite.

```
float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    // Do whatever you want with the color parameter
    // Sample texture but ignore color because it's not really a color
    return tex2D(TextureSampler, texCoord);
}

```

2) Implement your own `SpriteBatch` with a custom vertex struture that stores the additional information that you need for the shader, so that you do not need to change parameters between drawing each sprite. You can check the following question for some ideas on how to implement it yourself.

How exactly does XNA's SpriteBatch work?
> 3 votes

# Answer
if you set SpriteSortMode.Deferred the batch will be executed when Batch.End() is called...

You could use SpriteSortMode.Inmediate but it can hurts the perfomance...

The other options are building your own QuadRenderer or using deferred sort mode and call Begin/End for each parameter you need to pass.
> 1 votes

---
Tags: xna, c#, .net, fragment-shader
---


# Question
Title: Controls become inverted after a collision
I'm just prototyping a simple project. I'm moving a sprite on screen using the Xbox gamepad:

```
public override void Update(GameTime gameTime)
    {
        gamePad = GamePad.GetState(PlayerIndex.One);
        GetPlayerRotation();
        base.Velocity = new Vector2(vSpeed.X * gamePad.ThumbSticks.Left.X, -vSpeed.Y * gamePad.ThumbSticks.Left.Y);
        base.Update(gameTime);
    }

    private void GetPlayerRotation()
    {
        leftThumb = gamePad.ThumbSticks.Left;
        base.Rotation = -(float)Math.Atan2(leftThumb.Y, leftThumb.X);
    }

```

This works fine to move the sprite in the correct direction (Dependent on the angle of the joystick).

However, the problem is, when I try to do a collision with a simple test object that is just a sprite, with a rectangle:

```
        public virtual bool Collision(Entity entity1, Entity entity2)
    {
        if (entity1.Rectangle.Intersects(entity2.Rectangle))
        {
            Debug.WriteLine("Collision");
            return true;
        }
        else
            return false;
    }

            foreach (TestBlock block in blockList)
        {
            block.Update(gameTime);
            if(player.Collision(player, block))
            {
                player.vSpeed = -player.vSpeed;
            }
        }

```

Whilst this does work, and the speed is inverted, when the bool returns to false after the collision, the control scheme becomes inverted (I.e, pressing the thumbstick up moves the sprite down).

I was trying to achieve a simple bounce effect off the block.

# Answer
Your current collision response is flawed, since you are simply inverting the variable with your speed multiplier. The way you are using that speed multiplier in your Update() method would result in your controls being reversed.

What you need to do is create a collision response based on the two objects colliding. You can try to mimic the behavior by applying an impulse on the objects in the opposite direction:

```
entity.Velocity *= -(player.vSpeed * impulse);

```

which will give you a very poor collision response. This code is just an example. You can try to refine your own response.

Another option would be to use a physics engine, which would take many things into consideration, such as the mass, velocity, direction, rotation of both entities involved in the collision to provide a more realistic collision response.
> 2 votes

---
Tags: xna, collision-detection, xbox, gamepad
---


# Question
Title: What format(s) does Blender 2.6 support well enough to use with my game?
I'm using Blender 2.6 to create meshes to be loaded by my engine while in development. I've noticed that Blender 2.6 has very few exporters compared to previous versions of Blender (but a MUCH improved UI). I was using the FBX exporter since there is the FBX SDK to keep the model loading code from being too large (as opposed to a Collada parser). It seems that FBX wasn't such a good choice since I've started to notice that the exporter is terrible (It doesn't export light DecayType, material colors/intensity and many other things, it leaves them at zero).

What exporter in Blender DOES work well? I'd prefer one that exports to XML since it can be opened in a text editor to fix the paths.

# Answer
> 1 votes
The number of exporters is irrelevant, since you only need one!

The quality of the exporter is more important. If you're writing your own engine, I'd suggest you write your own Blender exporter so you can get it to work exactly the way you want it and support the same feature set that your engine does. The blender python API is easy to work with, the only drawback is that it's sometimes a moving target, meaning that scripts sometimes have to be updated when Blender is improved.

---
Tags: blender, file-format, model-loader
---


# Question
Title: Do "write once run anywhere" engines require platform specific code for multiplayer?
I've been investigating the myriad selection of mobile game dev engines that allow compilation of your code onto multiple target platforms, but, something I can't seem to figure out is if multi-platform "write it once" development is possible when you bring multiplayer into the equation.

I've looked at Unity and Monkey mostly, so far, but aside from seeing threads on the Monkey forum such as "I've developed such and such networking library for Monkey"... I can't find a definitive answer. That example is one of many that causes me concern.

Is it the case that if you used a cross platform engine, you'd have to write platform specific code **for the networking portion of your game/app?** (Even if the rest of the game did work on your target platforms with no/minimal platform-specific "jiggery".

I'm not talking about cross-platform multiplayer, but I do presume that'd be a happy by-product of a write-once-deploy-anywhere (within reason) networking solution.

# Answer
> 2 votes
Not being something that' I've personally tried with Unity (the whole networking part I mean), I can't give you a 100% sure answer, but I'm imagining that since whatever communication protocols Unity's using, they are (as standard networking protocols like TCP or UDP are) platform agnostic (i.e. if the platform supports TCP over IP, it will be able to connect to any other kind of platform that supports it).

Continuing on this, netoworking inside Unity should be platform agnostic as well. This question and answer on the Unity q&a site seems to support this:

http://answers.unity3d.com/questions/60247/cross-platform-network-transferring-variables.html

---
Tags: multiplayer, software-engineering
---


# Question
Title: SpriteBatch.Draw with scale or rotation trigger a new batch?
I recently read that any transformation changes will cause a new batch to be triggered.

So, if I have 10 Sprites and each has a different rotation or scale will there be 10 batches sent up?

Or is this somehow limited to SpriteBatch.Begin, where a Matrix is used?

I'm not clear on how the Begin/End relate to scale/rotation in draw calls or if they do at all in terms of how many batches are created.

I appreciate any info on this topic...

# Answer
No, individual batches will only be triggered in case you are using `SpriteSortMode.Immediate` or change texture. Individual sprite info is stored in an internal array and some operations are performed in CPU (rotation, scaling) before sending the vertex buffer to the GPU. For more information about the internals of SpriteBatch, check this answer.
> 3 votes

---
Tags: xna, performance, spritebatch
---


# Question
Title: Game theory games with very counter-intuitive results?
I have heard of an interesting game that produces a very counter-intuitive result. It is an auction of a $100 bill, but one in which both the first person in the auction and the second need to pay for the bill (while only the first one gets the bill). What is the most interesting, most often the bill is sold for over $100, sometimes going up to $500. The explanation is that the second-highest bidder doesn't want to lose a lot of money, so they opt to outbid the highest bidder by a bit to minimize their losses.

So my question is, what other game theory games are out there that produce very counter-intuitive results?

# Answer
> 2 votes
Go read about the Prisoner's Dilemma. It's kind of the mother of all of these. Goes like this:

> Two members of a criminal gang are arrested and imprisoned. Each prisoner is in solitary confinement with no means of speaking to or exchanging messages with the other. The police admit they don't have enough evidence to convict the pair on the principal charge. They plan to sentence both to a year in prison on a lesser charge. Simultaneously, the police offer each prisoner a Faustian bargain. If he testifies against his partner, he will go free while the partner will get three years in prison on the main charge. Oh, yes, there is a catch ... If both prisoners testify against each other, both will be sentenced to two years in jail.

Long story short, the optimal solution for each prisoner is to rat out the other, even though this is not as good a result as if each prisoner stayed quiet. The wikipedia page inked to above is pretty thorough and will provide you with a game-theory explanation as well as a great-many examples of the prisoners dilemma in the real world.

---
Tags: game-design, game-theory
---


title: Importing Fbx files

text:
# Question
Title: Importing Fbx files
I need to import a complex fbx model into C++. By complex I mean that it has a lot of vertices,cameras and so on.As far as I saw this is done using the ViewScene sample.I want to take that sample and make a new project but it gives me some linking errors such as:

```
1>  main.cpp
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall     SceneContext::SceneContext(char const *,int,int,bool)" (??0SceneContext@@QAE@PBDHH_N@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "bool __cdecl InitializeOpenGL(void)" (?InitializeOpenGL@@YA_NXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall SceneContext::~SceneContext(void)" (??1SceneContext@@QAE@XZ) referenced in function "public: void * __thiscall SceneContext::`scalar deleting destructor'(unsigned int)" (??_GSceneContext@@QAEPAXI@Z)
1>main.obj : error LNK2019: unresolved external symbol "public: bool __thiscall SceneContext::SetCurrentAnimStack(int)" (?SetCurrentAnimStack@SceneContext@@QAE_NH@Z) referenced in function "void __cdecl CreateMenus(void)" (?CreateMenus@@YAXXZ)
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall SceneContext::OnTimerClick(void)const " (?OnTimerClick@SceneContext@@QBEXXZ) referenced in function "void __cdecl TimerCallback(int)" (?TimerCallback@@YAXH@Z)
1>main.obj : error LNK2019: unresolved external symbol "public: bool __thiscall SceneContext::LoadFile(void)" (?LoadFile@SceneContext@@QAE_NXZ) referenced in function "void __cdecl DisplayCallback(void)" (?DisplayCallback@@YAXXZ)
1>main.obj : error LNK2019: unresolved external symbol "public: bool __thiscall SceneContext::OnDisplay(void)" (?OnDisplay@SceneContext@@QAE_NXZ) referenced in function "void __cdecl DisplayCallback(void)" (?DisplayCallback@@YAXXZ)
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall SceneContext::OnReshape(int,int)" (?OnReshape@SceneContext@@QAEXHH@Z) referenced in function "void __cdecl ReshapeCallback(int,int)" (?ReshapeCallback@@YAXHH@Z)
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall SceneContext::OnKeyboard(unsigned char)" (?OnKeyboard@SceneContext@@QAEXE@Z) referenced in function "void __cdecl KeyboardCallback(unsigned char,int,int)" (?KeyboardCallback@@YAXEHH@Z)
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall SceneContext::OnMouse(int,int,int,int)" (?OnMouse@SceneContext@@QAEXHHHH@Z) referenced in function "void __cdecl MouseCallback(int,int,int,int)" (?MouseCallback@@YAXHHHH@Z)
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall     SceneContext::OnMouseMotion(int,int)" (?OnMouseMotion@SceneContext@@QAEXHH@Z) referenced in function "void __cdecl MotionCallback(int,int)" (?MotionCallback@@YAXHH@Z)
1>D:\LuminusCore\Debug\LuminusCore.exe : fatal error LNK1120: 11 unresolved externals

```

I have added the Fbx includes/libs to the project, but I would like to know what else should I add in order to get rid of those errors.

Later Edit:

Sorry forgot to mention, I am using visual C++ 2010.

# Answer
> 2 votes
Regarding errors it looks like you have declarations but forgot to add definitions of virtual methods in derived class.

I don't know how you import fbx file content into your project but you can do the following (works in VS2012, I don't have access to VS2010 to check it):

* add fbx files as assets
* in build customization add MeshContentTask from your\_visual\_studio\_path\Common7\IDE\Extensions\Microsoft\VsGraphics\
* make sure fbx files have property Item Type set to Mesh Content Pipeline
* before compiling your main program Visual Studio will convert fbx files into cmo files and extract textures if they are packed together (into your debug folder by default)
* you have to parse cmo which is binary file yourself, it's fairly easy. You can find specification (and how to do this) in DirectX Tool Kit (ModelLoadCMO.cpp). Name of the converted file will be same as fbx but with cmo extension.

Edit: Be aware FBX files can either be binary or ASCII and either contain paths to textures or having textures packed inside. You can use FBX Converter 2013 by Autodek to switch and pack/unpack textures.

---
Tags: c++, fbx
---


# Question
Title: Increasing speed of circle over time as linear with Box2d
Assume that there is a circle and it can be moved by using keyboard arrows.Is required that increasing speed over time like increasing car speed. For example; max speed is 25 and time to reach max speed shall be 5 sec. Over 5 sec the speed will reach to max speed. Does Box2d handle that situation?. I tried `setting linear valocity` but it seems to make the circle have constant speed instead of increased speed over time.

Thank You!

Note: I'm using Box2DWeb Javascript port of Box2D.

# Answer
> 1 votes
With Box2D you should just have to apply an Impulse to your object, instead of setting the velocity manually.

```
ApplyImpulse(direction,point)  //Direction = vector

```

For the point, you can always use the center of your Body object by using:

```
Body.GetWorldCenter()

```

By applying small impulses, you will see your object accelerate. The speed of acceleration will depend on a bunch of variables, such as the force of your impulse, the weight of your object, friction, etc...

# Answer
> 0 votes
You'll have to time the amount of acceleration per frame yourself. There is no built-in function to increase velocity over time to a cap as you described. Extending Jon's answer, you probably end with up some code like this (adapted from http://www.iforce2d.net/b2dtut/constant-speed check it out the page, its very similar to what you want to to do):

```
timer = 5.0f; // 5 seconds
   update(float delta){
        timer -= delta; //timer keeps track of time left
        b2Vec2 vel = body->GetLinearVelocity();
        float desiredVel;
        if(timer > 0)
            desiredVel = MIN_VEL + * acceleration * delta; //m/s
        float velChange = desiredVel - vel.x;
        float impulse = body->GetMass() * velChange; //disregard time factor
        body->ApplyLinearImpulse( b2Vec2(impulse,0), body->GetWorldCenter() );
    }

```

---
Tags: javascript, box2d, html5, movement
---


# Question
Title: Collision detection in pong style multiplayer network game
I've recently implemented an authoritative server (node.js with socket.io) for a multiplayer pong game.

I've looked at client side prediction and fixing timesteps and starting to grasp the notion of simulated identical physics across server and clients.

However, I still can't quite figure out the approach to how to detect when the paddle truly hits the ball. The paddles can be controlled by touch or mouse movement which can be an almost instantaneous teleport to the location of the ball.

How can I determine if the paddle was in the right place at the right time taking into account the round trip time?

# Answer
> 2 votes
With an authoritative server, there is no way of being 100% fair without exposing the player to latency. There is always the possibility that the player made a sudden move that didn't reach the server before the ball passes the paddle, resulting in the player failing even when he should have hit it. But if the ping is low enough and 100% fariness is not required, you could be fine.

If 100% fairness is required and no latency is allowed, trusting the clients is the only option. This should be pretty straight forward. When the ball hits the player's paddle on client A, it tells about it to the others. When the ball hits the player B's paddle, client B again tells the others.

If the connection is very good, 100% fairness is required and the server has to be authoritative, it is still possible to make it using the lockstep protocol. This will introduce some latency but it might be ok with a proper connection. This was actually used as the first networking solution for Doom. In a nutshell, the game is divided into small, say 10ms, steps. On each step the client sends to the server any new player input instead of processing the input itself. At the end of the next step the server sends all received inputs back to the clients. On step 3, both clients process the inputs given on step 1 and so the games are exactly the same. If the server or the client hasn't received an input by the step it should have it, it locks until it's received. Hence the name lockstep I guess. A longer explanation can be found for example here and here.

# Answer
> -1 votes
I also tried to implement a real-time multiplayer pong using websockets and nodejs, there is a living instance here: http://www.pongoholic.com/

I went for a trust-the-client solution (exactly the second solution suggested by JohannesA). This ensures a 100% fairness, however, even the 60ms round trip time provided by websocket introduces latency in the game. I tried several solutions, such as dead reckoning, but none was 100% accurate.

Finally I had no time to test is, but I suppose that a good solution would be to use a mix of:

* **dead reckoning** user B sends to user A its position, velocity and a timestamp so that user A infer the current paddle position using a linear equation of motion:
current\_paddle\_position = previous\_paddle\_position + paddle\_velocity * delta\_t
This will help approaching the paddle from the ball but can introduce oscillations
* **artificial inteligence** (the AI term is *really* over the top here, but I did not know how to name it) Add an additional accelereration assuming that the player is trying to catch the ball with its paddle. This might reduce the oscillations while providing a good approximation of what the user is intenting. Finally:
current\_paddle\_position = previous\_paddle\_position + paddle\_velocity * delta\_t + ai\_acceleration * some\_tuning\_factor

At first I thought a pong-like would be the easiest game to try real-time multiplayer stuff, however it appeared that even the smallest latency is a lot for this type of game...

---
Tags: collision-detection, multiplayer, node.js, websocket
---