# Question
Title: Perpendicularity of a normal and a velocity?
I'm trying to fake angular velocity on my vehicle when it hits a wall by getting the dot product of the normal of the edge the car is hitting and the vehicle's velocity:

```
            Vector2D normVel = new Vector2D();
            normVel.equals(vehicle.getVelocity());
            normVel.normalize();
            float dot = normVel.dot(outNorm);
            dot = -dot;
            vehicle.setAngularVelocity(vehicle.getAngularVelocity() +
                    (dot * vehicle.getVelocity().length() * 0.01f));

```

outNorm is the normal of the wall.

The problem is it only works half the time. It seems no matter what, the car always goes clockwise.

If the car should head clockwise:

```
--------------------------------------
       /
      /

```

I want the angular velocity to be positive, otherwise if it needs to go CCW:

```
--------------------------------------
       \
        \

```

Then the angular velocity should be negative...

What should I change to achieve this?

Thanks

Hmmm...

Im not sure why this is not working...

```
        for(int i = 0; i < buildings.size(); ++i)
        {
            e = buildings.get(i);
            ArrayList<Vector2D> colPts = vehicle.getRect().getCollsionPoints(e.getRect());

            float dist = OBB2D.collisionResponse(vehicle.getRect(), e.getRect(), outNorm);
            for(int u = 0; u < colPts.size(); ++u)
            {
                Vector2D p = colPts.get(u).subtract(vehicle.getRect().getCenter());
                vehicle.setTorque(vehicle.getTorque() + p.cross(outNorm));
            }

```

# Answer
> 3 votes
The main problem is that the dot product of the velocity and wall normal is only based on the 'smallest' angle between these two vectors, so doesn't take into account if the vector is coming from the right or left.

You will need a vector **along** the wall and get the dot product of that and the vehicle velocity. The sign of the result will tell you whether to go cw or ccw.

Of course you can use the wall's normal to get the vector along the wall

```
Vector2D alongWall=new Vector2D(outNorm.y,-outNorm.x); //get perpendicular vector

```

So your code should look something like this;

```
       Vector2D normVel = new Vector2D();
        normVel.equals(vehicle.getVelocity());
        normVel.normalize();
        float dot = normVel.dot(outNorm);
        dot = -dot;
        Vector2D alongWall=new Vector2D(outNorm.y,-outNorm.x); //get perpendicular vector
        float cw=alongWall.dot(normVel);
        if(cw<0)//check which direction we are coming from
            dot=-dot; //coming from the right, so reverse direction of rotation

        vehicle.setAngularVelocity(vehicle.getAngularVelocity() +
                (dot * vehicle.getVelocity().length() * 0.01f));

```

# Answer
> 2 votes
**Just a moment**. (Ha ha, you'll get this at the end of this post).

The dot product between acute vectors (angle less than 90 degrees) is always positive. For obtuse angles the dot product is always negative. The force vector impacting the car points **opposite** the normal of the car usually, so the dot product of the force vector and the car surface normal is always obtuse (negative).

I don't think you should hack like this, doing the basic physics calculations is easier and will look a lot better.

A basic moment is computed as

```
moment = cross( r, F )

```
* **r** Is the vector from the centroid to the point of impact
* **F** is the force vector

If r x F is +, you have CCW rotation. If rxF is -, you have CW rotation. Note that you only need to do this in 2D, because the car is grounded.

Some examples of finding moments with basic vectors below. You should see that it checks out with your intuition based on the red dot car centroid.

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


title: Isometric projection bad coordonate

text:
# Question
Title: Isometric projection bad coordonate
I have a 2D map, for each element I apply this isometric projection to place my Sprite

```
 //Element e;
 float[] f= projection(e.getX(), e.getY() ,z);
         // x and y represent Sprite Coordonate (tile_width and height depend of my
         // camera size and the number of elements in x and in y
 float x =  f[0]*tile_width;
 float y =  f[1]*tile_height;

```

---

```
   public float[] projection(float x, float y, float z)
   {
     return new float[]{  (( x )-(y) ) , ((x/2) + (y/2) - z  )};
   }

```

the sprite for one element :

The result of my projection :

---

The problem is I need to add an offset of tile\_height/2 to the y and tile\_width/2 to the x to have something like this (in the red rectangle I drawed with paint what I want) :

**Where did I make wrong?**

(I found the projection method in How should I sort images in an isometric game so that they appear in the correct order? )

**edit : How I calculate my tile\_height and tile\_width :**

```
    tile_height = (float) ((CAMERA_HEIGHT/(game.map.getHeight()/2)));
    tile_width =  (float) ((CAMERA_HEIGHT/(game.map.getWidth()/2)));

```

# Answer
I am not sure how to create a single projection for multiplying with width and height, but I believe if you send the height and width along, the Projection would be:

```
public float[] projection(float x, float y, float z, float width, float height)
{
  return new float[]{
    (x * width / 2) + (y * width / 2),
    (y * height / 2) - (x * height / 2) - (z*height)
  };
}

```

Maybe have a look at 1ManBandStudios' post here.

I hope this helps :)
> 1 votes

---
Tags: isometric, andengine
---


title: Rain drops on screen

text:
# Question
Title: Rain drops on screen
I am trying to make simple rain drop effect on screen.Something like this
http://fc00.deviantart.net/fs20/f/2007/302/5/6/Rain\_drops\_by\_rockraikar.png

My idea is to:

Create small drop shaped normal textures, randomly put few on screen, apply texture perturbation and mix with current frame pixels.

Here are my questions:

* Does this idea even have sense? How professionals do this effect? Everything from text to code will be appreciated
* How to pass pixels to shader of already rendered frame?

# Answer
> 2 votes
Yes, that sounds like a reasonable approach. You'll want to generate a reduced size version of the current frame, for both efficiency and quality (good filtering) in the drop shader. You'll need to render your frame to an offscreen render target, then create a copy of it that is reduced to a smaller size. (You may need to do the reduction in several steps, like generating mipmaps.)

Then, to render the drops, you'd use the normal map to calculate the sample point in the texture. You could just negate the xy components of the normal and use that as the UVs (scale-biased to the \[0,1\] range), but if you're feeling fancy you could try doing the actual refraction math. (There is even a `refract` function in HLSL that will do most of the math for you.)

# Answer
> 0 votes
Im not familier with glsl or hlsl but I have done some XNA before. An idea that comes to mind is have a separate spritebatch (Like you might use for a simple ui that is drawn ontop of everything) And draw it either over or under the ui (Depending on what you want)

From there you can draw your drops, maybe have a few different shapes pre made and have them at the biggest size you wanted and scale down to the smallest you want and generate them at random. You could then have them slide down at a semi random speed (Maybe use the same value you used for size so the bigger the drop the faster it moves) And even draw a trail behind it if you wanted

---
Tags: xna, glsl, hlsl
---


# Question
Title: component Initialization in component-based game architectures
I'm develping a 2d game (in XNA) and i've gone slightly towards a component-based approach, where i have a main game object (container) that holds different components.

When implementing the needed functionality as components, i'm now faced with an issue -- who should initialize components?

Are components usually passed in initialized into an entity, or some other entity initialized them?

In my current design, i have an issue where the component, when created, requires knowledge regarding an attached entity, however these 2 events may not happen at the same time (component construction, attaching to a game entity).

I am looking for a standard approach or examples of implementations that work, that overcome this issue or present a clear way to resolve it

# Answer
> 3 votes
While some people create multiple specialized Entity classes for instantiating different types of entities it's not a great idea. Usually the entity should not have to initialize components itself. It is composed and not in charge of composing itself.

Entities should be built and fully initiated during one step, which means you shouldn't have to build any additional components after the entity has been created. But if for some reason you think you need to initialize or setup components later, you might want to do that from a ScriptComponent.

To take this approach even further you could even use a dedicated InitComponent which could be discarded after its first use.

---

I think the most common method of generating entities is achieved with Factories.

Some people build entire entities from files (level loading, scenario loading...) or network messages using a data reader and multiple factories (abstract factory pattern).

---

In some engines components are initialized with an entity ID (not your case apparently):

```
GameEngine gameEngine = //instantiate here;
//...
int entityId = 1003;
//...
PhysicsComponent phy = new BulletComponent(entityId, ...);
ScriptComponent act = new EnemyScriptComponent(entityId, ...);

gameEngine.GetPhysicsSystem().Register(phy);
gameEngine.GetScriptSystem().Register(act);

```

When you register this component to your engine the ID is then used to link it to a given entity.

So when the actor component is registered it could need the current position of the entity to instantiate/define some behavior:

```
class ScriptComponent : public Component
{
    int entityID;
    ...
    void OnRegister(GameEngine gameEngine)
    {
        PhysicsComponent phy = gameEngine.getPhysicsComponent(this.entityID);
        phy.GetPosition();
        ...
    }
}

```

The engine will call `OnRegister` on the newly registered component. You will want to make sure that your components can initialize properly by checking the order of the registrations or by delaying the call to `OnRegister`.

---

Another way of building components is to use a container entity (which seems to be your case):

```
GameEntity entity = new Entity(...);
//...
PhysicsComponent phy = new BulletComponent(...);
entity.addComponent(phy);

```

In this case the components registration to engines and unregistration is/could be managed by the GameEntity class.

In this case your entity can register each component and during registration your components will work the same way as in the previous example:

```
class ScriptComponent : public Component
{
    GameEntity entity;
    ...
    void OnAdded(GameEntity entity)
    {
        this.entity = entity
    }

    void OnRegister()
    {
        PhysicsComponent phy = this.entity.getPhysicsComponent();
        phy.GetPosition();
        ...
    }
}

```

In this case the `OnRegister` is called by the script system after the components have been attached to the entity. You can instantiate the desired behavior without worrying about the components registration order.

---

I for example never initialize any game related data in the constructor. Initializing components is done on `Init(params...)` this way I can preload them, reuse them, and init them one by one as data is loaded from a script, a file or from network.

---
Tags: xna, component-based, game-component
---


# Question
Title: Modular building technique with angles? (A roof)
Ive been spending a bit of time lately studying the modular buildings of many games and reading/viewing several tutorials about it as well, but almost every example I see uses a plain square building that does not have any angled roof or similar.

In all my applications (CS6, Blender/Max, UDK) I adhere to the same grid spacing and I get pretty good results, but trying to make modular angled pieces is confusing me as I'm not sure the best way to approach it.

Below is some shots of my template sheet and workflow I have been doing. Should I do the roof separately or is it possible for me to keep it in the same texture sheet?

The main issue is below. I have made a couple modular roof pieces but when i try to use them, i end up needing to model multiple other parts to fill gaps based on what roof shape i want. I then model those 'filler' pieces and now i have that much less space left in my texture sheet and those pieces are usually not that reusable for anything else. This is where im not sure how to proceed.

If anyone has any links to documents or papers talking about this or advice, I would greatly appreciate it! =-)

My main roof pieces with the gaps

*My power of 2 texture sheet, with 16x16 grid squares.*

*The texture sheet loaded into blender on a 16x16 plane and starting to separate and extrude.*

# Answer
If you are having trouble conceptualizing the modular pieces you need to create for buildings, I would recommend that you look to Lego. It will serve as both a practical example you can keep on your desk and is already highly modular.
> 3 votes

---
Tags: models
---


# Question
Title: How can I convert .obj files to .3ds on Mac?
I am on a Mac. I am currently looking for a tool that is able to **correctly** convert .obj files (Wavefront) to .3ds files (Autodesk 3ds Max).

I tried Blender but the exported file failed to include the smoothing groups.

What do you recommend I use?

# Answer
> 2 votes
Here's a link to the autodesk docs about importing .obj files in 3ds Max. The .3ds file format isn't something open and it's really tied to the internal workings of 3ds Max, so you can't really count on an external exporter or something like that.

Source: I worked on 3ds Max.

---
Tags: file-format, macos
---


# Question
Title: How to slow down a sprite that updates every frame?
I am going through a Allegro 5 tutorial which has a game loop.

There is also a variable "active" which determines if a key is being held down. Thus if the left key is being held down active is on and it begins looping through the row on the sprite sheet that corresponds to moving left.

The problem is that this logic is checked everytime the loop is performed thus at approximately 60 fps the three images that are used to do the left walking animation cycle round super fast which means my character looks like it is in a rush.

Total beginner question: so what is the correct way to slow down the transition between sprites so that the walking looks like it is done at a moderate pace.

Here is the code used to transition across the sprite between the three different phases of the person walking:

```
        if (active) {
            sourceX += al_get_bitmap_width(player) / 3;
        } else {
            sourceX = 32;
        }

        if (sourceX >= al_get_bitmap_width(player)) {
            sourceX = 0;
        }

```

I can kind of guess what it should be in plain English: *update sourceX only every certain part of a second* but I can't think of how to put this into code.

# Answer
You're on the right track; you just need to throw in a system to regulate the timing with which the sprite is updated. The exact model you use is up to you - essentially whatever concept you like working with. In the example I will provide you can specify the speed of the animation in frames per second (independent from the FPS of your game, of course). Alternatives would be animation speed on a `0` to `1+` scale, or directly specifying the amount of time between each animation swap.

With the 'frames per second' method, you can declare your animation speed as follows:

```
float animationSpeed = 5.0f;

```

Here I've chosen to run the animation at 5 frames per second. Whatever rate is chosen, it means that every `1.0f / animationSpeed` seconds, the sprite's frame has to be updated, giving the following:

```
float animationUpdateTime = 1.0f / animationSpeed;

```

You also need to keep track of the time since your last update:

```
float timeSinceLastFrameSwap = 0.0f;

```

And every frame you will add `deltaTime` to this, assuming that you already have a system in place for obtaining the `deltaTime` of the frame:

```
timeSinceLastFrameSwap += deltaTime;

```

Note that you'd only do this when `active` is `true` \- when your sprite is animating. When `timeSinceLastFrameSwap` exceeds `animationUpdateTime`, you can increase `sourceX` and reset `timeSinceLastFrameSwap`, so the whole update would look like this:

```
if (active) {
    timeSinceLastFrameSwap += deltaTime;
    if (timeSinceLastFrameSwap > animationUpdateTime) {
        sourceX += al_get_bitmap_width(player) / 3;
        timeSinceLastFrameSwap = 0.0f;
    }
    if (sourceX >= al_get_bitmap_width(player)) {
        sourceX = 0;
    }
} else {
    sourceX = 32;
    timeSinceLastFrameSwap = 0.0f;
}

```

Happy coding!
> 3 votes

# Answer
You can add a local variable `i`, which you will increase each every frame `i++`. Then you can update your animation each frame when `i mod 10 == 0` to update animation at 6fps slower.

EDIT: This is not recommended solution for the most of the cases. Usually your animation should depend on time, not the render speed. See the other answer for explanation and details.
> 0 votes

---
Tags: c++, game-loop, timing, allegro
---


title: Doubling the DPI with a shader?

text:
# Question
Title: Doubling the DPI with a shader?
I'm developing a game where the map is generated with Perlin Noise, but on the CPU. I am generating some perlin noise onto a texture with a small size, and then I stretch it out to the whole screen to simulate a map.

The reason for the CPU generating the noise is that I want it to look the same on all devices.

Now, here's the end-result.

Please ignore the bullets and the explosion on the picture. What matters is the background (the black/gray pixels) and the ground (the brown-ish pixels). They are rendered to the same texture through perlin noise.

However, this doesn't look very pretty. So I was wondering if it would be possible to double the amount of pixels using a shader, and rounding edges at the same time? In other words, improve the DPI.

I'm using SharpDX with DirectX 11, through its toolkit feature. But any help that'll lead me in the right direction (for instance through HLSL) would be a great help.

Thanks in advance.

# Answer
You could try HQx or xBR filters. They are used e.g. in NES / SNES emulators to upscale pixel graphics.
> 3 votes

# Answer
If you're using a monochrome noise texture, with a color ramp in the shader to apply the brown-red and blue-black colors to different ranges of noise, then you could probably get some interesting results by using a second copy of the noise texture (or a different noise texture) scaled down and added to the first. It would be effectively a detail map. Adding the two noise values together before applying the color ramp should have the effect of breaking up the pixellated features and creating an irregular coastline. You'd probably also want to turn on bilinear filtering for the noise textures, as you're using nearest-neighbor now.
> 0 votes

---
Tags: hlsl, resolution, sharpdx
---


# Question
Title: Farseer Physics Engine and the Ms-PL License
Am I able to produce code for a game which uses the VelcroPhysics engine and release my code under an open source license other than the Ms-PL?

My concern is with the following section from the license:

> If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.

If I do not include Farseer in my source code distribution does this give me an exemption from this clause as I am not distributing the software? My code merely uses its functions. No where in the license does it force you to provide source code for derivative works or linking works, it simply gives you the option of "if you distribute".

# Answer
> 1 votes
Thanks to Maik Semder for his google-fu this question is already answered here.

---
Tags: legal, licensing, open-source, velcro-physics-engine
---


title: Direct3d - Code structure

text:
# Question
Title: Direct3d - Code structure
I'm learning directx in a master's degree and they taught us to have a GraphicsLayer class which is the one connecting with the direct3d library. That way this class is completly independent from the other classes (my game classes), meaning changing the renderer to OpenGL wouldn't require much effort but only changing the graphicLayer.

This classe has it's LoadAssets, Paint methods, but I have a question, they told us to load all the assets inside this class. This means all these methods will be in the loadAssets method:

```
D3DXCreateTextureFromFileEx(g_pD3DDevice,"tiles.png",0,0,1,0,D3DFMT_UNKNOWN,D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,NULL,NULL,NULL,&texTiles);
// And more resources to load
//...

```

texTiles as you see is a LPDIRECT3DTEXTURE9 instance which is declared in the graphicLayer.h.

So my question is, how do you manage all the resources? Do I have to declare in the .h all my game textures even if I'm not using them? How would you load only those resources there are in a scene and draw them in a code-strucured way?

# Answer
The interesting thing about programming is that there is an infinite number of ways to do things. Give a problem to 10 programmers, and you get 10 completely different solutions. Just because you are *told* to do it that way, doesn't mean that it's the *only* way to do it.

Hardcoding the filenames of assets in your code is usually a bad design, because it makes the renderer a lot less flexible and prevents the separation of game engine and game content (imagine you are working with a graphic artist who has to call you whenever they want to add a new texture).

Usually, when you load a map in a game, you have that map in some kind of file. So you pass that file to your graphic engine to load it. This file usually contains a list of asset files which are used in that map. So the graphic engine will load these assets when it parses the map file.

To safe memory and reduce initial loading times, an engine could also load certain assets on demand. An example would be an enemy which is spawned on the map while playing. The engine could wait with loading the geometry and texture of that enemy until it is spawned, and free that memory when the enemy is removed.

In one game project I took part in, we managed all assets through a ResourceManager class. This class would cache all loaded resources. So when you need the texture xyz anywhere, you call ResourceManager.getTexture("xyz.png"). When it's the first call, it loads that texture from disk. At subsequent calls, it returns a cached copy. The resource manager automatically frees any cached assets which weren't requested for over a minute, except those which have a "never drop" flag set (for assets which are used infrequently, but when they are used they are time-critical).
> 0 votes

---
Tags: c++, directx, data-structure, directx9
---


# Question
Title: Calculate an AABB for bone animated model
I have a model that has its initial bounding box calculated by finding the maximum and minimum on the x, y and z axes. Producing a correct result like so:

The vertices are then stored in a VBO and only altered with matrices for rotation and bone animation. Currently the bounds are not updated when the model is altered. So the animated and rotated model has bounds like so:

*(Maybe it's hard to tell, but the bounds are the same as before, and don't accurately represent the rotated/animated model)*

So my question is, how can I calculate the bounding box using the armature matrices and rotation/translation matrices for each model? Keep in mind the modified vertex data is not available because those calculations are performed on the GPU in the shader.

The end result I want is to have an accurate AABB the represents the animated model for picking/basic collision checks.

# Answer
You could precalculate a bounding box in bone local space for each bone, using just the vertices that have a non-zero weight for that bone. At runtime, transform each of these boxes to world space using the bone matrices for the current pose, then calculate an AABB that encloses all of the bone boxes.

The AABB calculated this way will likely be a bit larger than strictly necessary, because of the extra space taken by the bone boxes, but it should be better than what you have now. Also, after checking for collisions against the whole model AABB you could then check for collisions against the individual bone boxes to get a more precise result, if you wish.
> 10 votes

# Answer
First, it depends on the purpose of the bounding volume.

Normally, bounding volume is used for culling (view frustum culling, occlusion culling, etc.).

As you do skinning on GPU, you have already rendered the model before generating the bounding volume for culling.

Therefore, you should compute the conservative bounding volume as tight as possible on CPU.

There are several methods for this.

1. Manually create a static bounding volume.
2. Compute the longest bone chain from root bone, and then use it to generate a bounding sphere. The advantage is that no matter what animation applies (no scaling/translating), you need not to update the bounding sphere. Disadvantage is that the sphere is static and often too big.
3. Compute AABB/OBB from all OBB/Capsule of bones in the current poses. It needed to be done after animation update. A little bit more complicated but creating tighter bounding volume than method 2.
4. Similar to method 2, but just treats bones as line segments. Finally expand the OBB by a constant radius (maximum distance between vertices and their associated bones).

These solutions trades accuracy with run-time performance. If the created bounding volume is conservative (not culled incorrectly), then you may choose any one that suits.
> 9 votes

---
Tags: 3d, skeletal-animation, aabb
---


title: How to make a iOS plugin for Unity3d

text:
# Question
Title: How to make a iOS plugin for Unity3d
I've passed last 2 days reading articles and book for understand how can i make a plugin for iOS in Unity. Basically i need just a demo for understand how it work. For now i've tried to make this process (with really poor luck):

I've started a new project in Unity and writed a simple script

```
using UnityEngine;

using System.Collections;

using System;

using System.Runtime.InteropServices;

public class CallPlugin : MonoBehaviour {

    [DllImport ("__Internal")]

    private static extern int test();

    void Start ()

    {

        Debug.Log(test());

    }

}

```

Then i've created a project in Xcode with this simple script:

```
extern "C"{

    int test()

    {

       int che = 5;

        return che;

    }

}

```

Then i've tried:

to put the .mm and .h in the Assets/Plugins/iOS = nothing

to build the unity project and than add the .h and .mm in the Xcode project = nothing

In Unity i will always get the EntryPointNotFoundException, so unity see the file but is unable to reach the method. The problem is... how?! :)

Maybe i miss something or i've done something wrong? Thanks a lot for every help that you can give me :)

# Answer
Ok, after reading a lot i've found the solution:

Seems that the extern call don't work inside the editor or simulator, so the correct way of doing this is develop for device (after putting the header and the implementation files under Assets/Plugins/iOS).

I hope that this will help some one :)
> 8 votes

---
Tags: c#, unity, ios, objective-c
---


# Question
Title: Cloning a Game - Dev diary while using original assets
I'm currently cloning a game and still using the sound and graphic assets of the original.

I know that I may not distribute those assets but what about publishing a video of my progress as part of a dev diary, is that allowed?

Thanks.

# Answer
Unless you obtain written consent from the owner, **probably not**. This is one way of distributing the assets, after all. Maybe that's some kind of fair use but I wouldn't bet on it, so your best option is just to ask for permission.
> 2 votes

---
Tags: legal
---


# Question
Title: I enabled and setup glBlendFunc, but my texture has a white outline. What am I doing wrong?
You can see most of my source code in this question: Instead of the specified Texture, black circles on a green background are getting rendered. Why?

Now I have the problem, that my texture has a white outline on its transparent parts. After googling and setting up glBlendFunc, the outline just got "softer".

This is how it looks like:

This is how I now setup OpenGL:

```
    public static void SetupGL()
    {
        GL.Enable(EnableCap.Blend);
        GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

        GL.Enable(EnableCap.Texture2D);
        GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

    }

```

# Answer
You should use pre-multiplied alpha for transparent textures that you intend to do alpha blending on. That will solve the color bleeding you're seeing.

First, make sure to multiply the RGB values of your texture with the A.

Second, use glBlendFunc(GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA) as the blend mode.
> 6 votes

# Answer
You should try setting your textures to `GL_NEAREST`. It looks like you're using `GL_LINEAR` which could make your textures not be "crisp" on the edges where you want them to be.
> 1 votes

---
Tags: c#, opengl, opentk
---


# Question
Title: How to create a thread in XNA for pathfinding?
I am trying to create a separate thread for my enemy's A\* pathfinder which will give me a list of points to get to the player. I have placed the thread in the update method of my enemy. However this seems to cause jittering in the game every-time the thread is called.

I have tried calling just the method and this works fine. Is there any way I can sort this out so that I can have the pathfinder on its own thread? Do I need to remove the thread start from the update and start it in the constructor? Is there any way this can work?

Here is the code at the moment:

```
bool running = false;
bool threadstarted;
System.Threading.Thread thread;

public void update()
{
    if (running == false && threadstarted == false)
    {
        thread = new System.Threading.Thread(PathThread);

        //thread.Priority = System.Threading.ThreadPriority.Lowest;
        thread.IsBackground = true;
        thread.Start(startandendobj);
        //PathThread(startandendobj);
        threadstarted = true;
    }
}

public void PathThread(object Startandend)
{

    object[] Startandendarray = (object[])Startandend;
    Point startpoint = (Point)Startandendarray[0];
    Point endpoint = (Point)Startandendarray[1];

    bool runnable = true;
    // Path find from 255, 255 to 0,0 on the map
    foreach(Tile tile in Map)
    {
        if(tile.Color == Color.Red)
        {
            if (tile.Position.Contains(endpoint))
            {
                runnable = false;
            }
        }
    }
    if(runnable == true)
    {
        running = true;
        Pathfinder p = new Pathfinder(Map);
        pathway = p.FindPath(startpoint, endpoint);
        running = false;
        threadstarted = false;
    }
}

```

# Answer
> 7 votes
*I don't know why 2 people voted to close this as I think it is a legitimate questions that isn't more localized than XNA and threading*

Starting a new thread is relatively expensive and might cause a tiny bit of jittering when you only have 15ms to build a new frame. The best way to overcome this is by using the a thread pool. Here you park a few threads so that you don't have the overhead of creating a new one every time you need one to do some work. You can roll your own thread pool to get maximum control but .NET also has a built in thread pool ThreadPool that also does so managing so that you dont get too much threads running at once.

What is also important, and for me that wasn't really clear from your example, is that your thread doesn't have to finish in the same update loop iteration. Don't wait for the thread to finish. Just check every frame if the path is ready and use it when it is.

Lastly take care to make your code thread safe and make sure there is as little interaction between threads as possible (safer and faster).

# Answer
> 0 votes
What i´ve learnd of threading is that you create one or more thread(s), and run it parrallel with the game, nonstop. and when you need data there procsed, you simply push a job (a function with data) to that thread and it will take care of it, and when it´s done doing that it just keeps running. That way you dont have to start threads more thane once. and you can push plenty of data there. and if you need an absolut finish state at a specific frame, you could go with some sync callback in the job function.

and as Roy T. states, make your code thread safe. it´s wery important.

---
Tags: xna, c#, path-finding, multithreading, .net
---


# Question
Title: Procedural generation of physics-enabled structures (in a 2D world)
Is it possible to procedurally generate stable structures out of rigidbody objects at a reasonable runtime speed? Imagine Angry Birds's levels kind of structures but generated procedurally.

# Answer
> 5 votes
I think the crucial part of this question is how you can procedurally generate stable structures (as generating an unstable pile of blocks in real time should be no problem)

My approach would be to prebuild sub structures that are guaranteed to be stable. Have each substructure store two sets of spans" * one for the bottom where it requires contact below it. * one for the top where it has stable sections that can support sub structures above it.

I'd start with subsections that have perfectly level spans and get that working first, then you could add information to each subsection for the amount of slope it can tolerate below it. (this might be pretty tricky as the center of mass changes the way the structure below will deal with the lateral force of friction)

It's worth noting that this method doesn't support some types of stable block piles. All of the sub structures need to be stable on their own. (i.e. you couldn't have a structure that requires a heavy structure above it to hold down some off balance lever)

After that is working you could probably layer on some more sophisticated stability analysis to handle the more exotic substructure types.

Matching up the contact patches exactly will be a key part of making these structures stand up - tiny gaps or interpenetration will cause real problems. It will also help to make sure that the rigid bodies are created already "asleep".

# Answer
> 1 votes
Of course it can be, but it won't be easy. Look at Spore by EA, they did it in 3D, and their level of freedom in designing your creatures there is amazing, and your creations there are complex simulated living organisms. What you want is something much simpler. What you will need is a validation system to follow a set of rules. You can't just go off randomly throwing objects on top of each other. Otherwise most of your procedurally generated structures will tumble down once they the physics engine kicks in. Good luck.

---
Tags: physics, procedural-generation, rigid-body-dynamics
---


# Question
Title: Recommended formats to store bitmaps in memory?
I'm working with general purpose image rendering, and high-performance image processing, and so I need to know how to store bitmaps in-memory. (24bpp/32bpp, compressed/raw, etc)

What is the "usual" or "normal" way to store bitmaps in memory? (in C++ engines/projects?)

How to store bitmaps for high-performance algorithms, such that read/write times are the fastest? (fixed array? with/without padding? 24-bpp or 32-bpp?)

How to store bitmaps for applications handling a lot of bitmap data, to minimize memory usage? (JPEG? or a faster \[de\]compression algorithm?)

I'm not working with 3D graphics or DirectX / OpenGL rendering and so I don't need to use graphics card compatible bitmap formats.

---

Some possible methods:

* Use a fixed packed 24-bpp or 32-bpp `int[]` array and simply access pixels using pointer access, all pixels are allocated in one continuous memory chunk (could be 1-10 MB)
* Use a form of "sparse" data storage so each line of the bitmap is allocated separately, reusing more memory and requiring smaller contiguous memory segments
* Store bitmaps in its compressed form (PNG, JPG, GIF, etc) and unpack only when its needed, reducing the amount of memory used. Delete the unpacked data if its not used for 10 secs.

# Answer
> 5 votes
For fast software rendering, there are a few things you really want:

16-pixel scanline alignment, for SIMD or vectorized code.

32-bit RGBA or BGRA chunky (as opposed to planar) pixel formats, for fast 4-byte indexing. BGRA for fast copying to video memory for display, or RGBA because that's how image data is usually stored in files. If no alpha is needed, you still want to pad the data to 4 bytes per pixel.

If the image is too large, you'll get expensive cache misses. Keep the image size down, or split the image into tiles.

Working with compressed image formats in software is usually too expensive. For hardware, S3TC and other texture compression formats are commonly used. They are extremely bad quality lossy compression, but work well for the types of images usually used for textures. Their biggest benefit is being fixed size, so to access a given pixel you only need to read and decode one block of data at a known location.

# Answer
> 2 votes
1. Pixel arrays with/without tiling.
2. You should use tiling if you intend to do efficient scaling / interpolation / software rendering since it improves the chances of finding the next accessed pixel still in cache. 32 bits per pixel (with the appropriate alignment) are preferred since there are some CPU-specific optimizations for accessing correctly aligned data.
3. JPEG is lossy, PNG with max. compression is slow. You'll probably need to add some implementation specific compression step, if there is one.

---
Tags: c++, graphics, performance, image, memory-efficiency
---


title: Simpler alternative to AngelScript

text:
# Question
Title: Simpler alternative to AngelScript
I want to give players the ability to create and share bullet patterns for a shoot'em up.

The pattern scripts should have all the common programming stuff like loops, if/else, variables, and so on.

But in the end, I just want them to call a "spawn bullet at X, Y with Z angle and A speed" in the C++ game.

To spawn a circle of bullets, the user should only have to write a script with a for loop that goes from 0 to 360 and calls the spawn bullet function on every iteration.

I tried integrating AngelScript, but I am getting nowhere - it looks way to complex for a simple task like this one.

Is there an easy to integrate library that can solve my problem? Thanks.

# Answer
> 3 votes
Embedding scripting is never easy.

Squirrel or Lua might be simpler as long you don't plan to use classes. For example you probably won't need a class for the bullets, a function SpawnBullet(x, y, angle, speed) would probably be enough. (If you need classes AngelScript takes quite a bit of work from your shoulders because it was designed to interact with C++ classes in the first case.)

---
Tags: c++, scripting
---


# Question
Title: What's a good way to programmatically manage a cloneable entity?
Say you have missiles or rockets that a player can fire.

What's a good way to *programmatically* manage the cloning of a base rocket, for example?

I can think of 2 ways to do it:

* Player has a currently selected weapon (which is an int)
* When player shoots, the `selectedWeapon` member is looked at, and the correct instance of rocket is created (with some base parameters)

Or

* Player has a currently selected weapon (which is a pointer, to a "base instance" of the rocket object)
* When player shoots, the base instance rocket is cloned, transformed, and shot into the game world

# Answer
In general terms, you're talking about the difference between the Factory pattern - a piece of code that creates objects based on being told which type to make - and the Prototype pattern - a piece of code that creates objects by copying an existing object.

In cases like this, I think the prototype pattern is the wrong way to go. A rocket will have several aspects (position, velocity, orientation, etc) which only make sense once it's in the world, and there are very few values that you would want to copy that are useful anyway. So to have a rocket object hanging around attached to the player with several values that are redundant feels like a poor approach. Your rockets probably contain no state that needs to be copied from a prototype, so just create them when needed and set up the values accordingly.

Where the prototype pattern is useful is when you want to be able to define cloneable objects from within the application - eg. a player can design his own rocket type, and then fire them later. Then it would make sense to store their design as a prototype.
> 2 votes

# Answer
The former makes slightly more sense. Think of weapons that fire multiple projectiles or random projectiles. Better to have data that defines what to fire and how and then use that rather than attaching a single object.

Besides, if the player had to hold and instance of a projectile to fire it, how and when do you set that up? Your weapon power ups and such will need some way of defining what projectile to give to the player, so by storing only the cloneable instance you'll only have moved the problem rather than having solved it.
> 0 votes

---
Tags: c++, instancing
---


# Question
Title: MMORPG Server architecture: How to handle player input (messages/packets) while the server has to update many other things at the same time?
This is more or less like what I'm thinking up to now:

```
while(true)
{
    if (hasMessage)
    {
        handleTheMessage();
    }
}

```

But while I'm receiving the player's input, I also have objects that need to be updated or, of course, monsters walking (which need to have their locations updated on the game client everytime), among other things.

What should I do? Make a thread to handle things that can't be stopped no matter what? Code an "else" in the infinity loop where I update the other things when I don't have player's input to handle? Or even: should I only update the things that at least one player can see? These are just suggestions... I'm really confused about it. If there's a book that covers these things, I'd like to know.

It's not that important, but I'm using the Lidgren lib, C# and XNA to code both server and client.

# Answer
This is quite a basic question, although it might not seem like one. Networked games are no different to any other program in this regard - if you need the program to be responsive, you really have 4 options, listed in the order you should attempt them:

1. make sure each operation is processed quickly (by disallowing any slow operations)
2. set up slow operations so that they can be time-sliced and process a small part of it at a time until it's done
3. split slow operations into multiple quick ones and process each part separately
4. process slow operations in a separate process or thread, using (sometimes complex) synchronisation methods to communicate

90% of the time you can just go with the first option (changing a value, requesting some data). Most of the remainder are in the second category (eg. following a path).
> 4 votes

# Answer
my network server engine has this architecture and has 3 main threads: SocketServerThread, ScheduledThread, GameServerThread. Game data is stored into DB, so there are other threads for DB connections (using a connectionPool)

-SocketServerThread manages all I/O data and new connections. When this thread receives data, it build a "input" message like (lenght:short, code:int, data:bytes) and send it to a shared structure: inputPriorityQueue. SocketServerThread produces "input" message and the only one that consume "outputMessage"

ScheduledThread manages specific scheduled events (game logic events and general server events) These events aren't generated by players inputs/actions, but usually by interal Cron jobs or scheduler. Example of these events are Monster AI, or player logout per x seconds inactivity. This thread can generate "input" message too, and put them in the "inputPriorityQueue" (processed by GameServerThread) or output messages, processed by SocketServerThread.

Then Another thread, GameServerThread, read "messages" from inputPriorityQueue, process them, update game server status and produces messages in the outputPriorityQueue.

SocketServerThread every 35ms reads all message it could read from "outputPriorityQueue" in a fixed maximum interval (for example 20ms), then for the other 15ms it is free to manage socket new connections and socket new incoming data. SocketServerThread Appends all socket avaible data into the Client buffer data, and checks this client buffer data for composing all "input" message it cans.

SocketServerThread is the only one who can consume outputPriorityQueue message.

The queues(input and output) are Priorityqueue, so i can manage message processing order.. for example, a server message like: "Server will be restarted in 30 seconds" could have a higher priority and processed immediatly.
> 1 votes

# Answer
The MMORPG server I am currently developing solves this problem with multi-threading. This is a simplified overview of the architecture:

One thread is listening to the client connections, interprets the data streams, and breaks them up into "event objects" which are then pushed onto an event queue.

Another thread handles the game loop. The loop starts with clearing the event queue. It then acts on the events and performs all other game logic.

When the game loop does something one or more clients need to be informed about, it will also create events. These events are collected in separate event queues for each client. A third thread serializes these events and sends them to the clients.

This architecture has the advantage that both input and output are completely separated from the game logic.

The biggest problem in such a multi-threaded architecture is to avoid concurrent access to the event queues. When one thread reads a queue while another one writes to it, you can run into all kinds of obscure bugs. So it's important to learn about the thread synchronization tools your programming language / platform / threading framework provides and use them correctly.
> 0 votes

---
Tags: xna, networking, mmo
---


# Question
Title: What is the easiest and shortest way to draw a 2d line in c/c++?
I am fairly new to c/c++ but I do have experiance with directx and opengl with java and c#. My goal is to create a 2d game in c with under 2 pages of code. Most of what I have seen requires 3 pages of code to just get a window running.

I would like to know the shortest code to get a window running where I can draw lines. I believe this can be done in less lines with opengl versus directx. Is there maybe an api or framework i can use to shorten it more?

Also, it would be nice if the solution were cross platform compatible.

# Answer
GLUT might be what you're looking for. It is a cross platform Open GL wrapper that helps setting up the basics.

Hope this helps.
> 2 votes

# Answer
http://www.sfml-dev.org/ \<- Making window, and drawing lines is very easy
> 3 votes

# Answer
Here is an example program that draws a line to a window using the cross platform library Qt. Includes have been omitted.

```
struct MyWindow: public QMainWindow
{
  Q_OBJECT

  MyWindow(QWidget *parent = 0, Qt::WFlags flags = 0){ui.setupUi(this);}
  ~MyWindow(){}

  void paintEvent(QPaintEvent *)
  {
    QPainter painter(this);
    painter.setPen(Qt::blue);

    QLineF line(10.0, 80.0, 90.0, 20.0);
    painter.drawLine(line);
  }

  Ui::MyWindow ui;
};

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MyWindow w;
  w.show();
  return a.exec();
}

```

Note that this example does not use OpenGL. To render to OpenGL using the same draw calls simply derive a class from QGLWidget.
> 3 votes

# Answer
Also look at SDL. A good wrapper multiplatform to Directx (on Win)and OpenGl (on Linux and also Win ..). I'm using SDL and... it is easy to understand for a beginner!

For Sdl exists a binding to C# and Java. For C# is called. SDL.NET
> 2 votes

# Answer
You might want to use Cairo to draw 2d graphics on any backend. You can combine it with SDL or OpenGL or GTK, as display-backend, or with .png or .svg or .pdf as file-backend, too.
> 0 votes

# Answer
Here's a basic GLUT app that draws lines

```
#include <gl/glut.h>
#include <math.h>

void render()
{
  glClear( GL_COLOR_BUFFER_BIT );

  glBegin(GL_LINES);
  for( double i = 0 ; i < 2*3.14159; i+=0.01 )
  {
    double value1 = cos(i) ;
    double value2 = sin(i) ;
    glColor3d( fabs(value1), fabs(value1)*fabs(value2), fabs(value2) );
    glVertex2d( .2*value1*value2,.4*value2 ) ;
    glVertex2d( value1, value2 ) ;
  }
  glEnd() ;

  glutSwapBuffers() ;
}

int main( int argc, char** argv )
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
  glutInitWindowPosition(120,260);
  glutInitWindowSize(600,600);
  glutCreateWindow("GLUT Window");

  glutDisplayFunc( render );
  glutMainLoop();
}

```
> 0 votes

---
Tags: c++, opengl, directx
---


# Question
Title: How to make a stack stable? Need help for an explicit resting contact scheme (2-dimensional)
Previously, I struggle with the sequential impulse-based method I developed. Thanks to jedediah referring me to this paper, I managed to rebuild the codes and implement the simultaneous impulse based method with Projected-Gauss-Seidel (PGS) iterative solver as described by Erin Catto (mentioned in the reference of the paper as \[Catt05\]).

So here's how it currently is:

1. The simulation handles 2-dimensional rotating convex polygons.
2. Detection is using separating-axis test, with a SKIN, meaning closest points between two polygons is detected and determined if their distance is less than SKIN.
3. To resolve collision, simultaneous impulse-based method is used. It is solved using iterative solver (PGS-solver) as in Erin Catto's paper. Error-correction is implemented using Baumgarte's stabilization (you can refer to either paper for this) using J V = beta/dt\*overlap, J is the Jacobian for the constraints, V the matrix containing the velocities of the bodies, beta an error-correction parameter that is better be \< 1, dt the time-step taken by the engine, and overlap, the overlap between the bodies (true overlap, so SKIN is ignored).

However, it is still less stable than I expected :s I tried to stack hexagons (or squares, doesn't really matter), and even with only 4 to 5 of them, they would swing! Also note that I am not looking for a sleeping scheme. But I would settle if you have any explicit scheme to handle resting contacts.

That said, I would be more than happy if you have a way of treating it generally (as continuous collision, instead of explicitly as a special state).

Ideas I have tried: Using simultaneous position based error correction as described in the paper in section 5.3.2, turned out to be worse than the current scheme.

If you want to know the parameters I used:

* Hexagons, side 50 (pixels)
* gravity 2400 (pixels/sec^2)
* time-step 1/60 (sec)
* beta 0.1
* restitution 0 to 0.2
* coeff. of friction 0.2
* PGS iteration 10
* initial separation 10 (pixels)
* mass 1 (unit is irrelevant for now, i modified velocity directly\<-impulse method)
* inertia 1/1000

Thanks in advance! I really appreciate any help from you guys!! :)

EDIT

In response to Cholesky's comment about warm starting the solver and Baumgarte: I forgot to mention! I do save the contact history and the impulse determined in this time step to be used as initial guess in the next time step.

As for the Baumgarte, here's what actually happens in the code. Collision is detected when the bodies' closest distance is less than SKIN, meaning they are actually still *separated*. If at this moment, I used the PGS solver without Baumgarte, restitution of 0 alone would be able to stop the bodies, separated by a distance of ~SKIN, in mid-air! So this isn't right, I want to have the bodies touching each other. So I turn on the Baumgarte, where its role is actually to pull the bodies together! Weird I know, a scheme intended to push the body apart becomes useful for the reverse.

Also, I found that if I increase the number of iteration to 100, stacks become much more stable, though the program becomes so slow.

UPDATE

Since the stack swings left and right, could it be something is wrong with my friction model?

Current friction constraint: relative\_tangential\_velocity = 0

# Answer
> 2 votes
Are you maintaining contact history from frame to frame so you can warm start the solver? I wouldn't expect to be able to support stacking of more than a few bodies without temporal coherence.

It's also worth making sure you have a threshold that allows for a tiny bit of overlap before apply baumbarte stabilization so things aren't too "bouncy."

ie. if(penetration \> someEpsilon) stabilization = stabilizationFactor * (penetration - someEpsilon)

---
Tags: 2d, rotation, collision-resolution, physics-engine
---


# Question
Title: Issues with shooting in a HTML5 platformer game
I'm coding a 2D sidescroller using only JavaScript and HTML5 canvas, and in my game I have two problems with shooting:

1) Player shoots continous stream of bullets. I want that player can shoot only a single bullet even though the shoot-button is being held down.

2) Also, I get an error "Uncaught TypeError: Cannot call method 'draw' of undefined" when all the bullets are removed. My shooting code goes like this: When player shoots, I do `game.bullets.push(new Bullet(this, this.scale));` and after that:

```
    function Bullet(source, dir)
    {
        this.id = "bullet";
        this.width = 10;
        this.height = 3;
        this.dir = dir;

        if (this.dir == 1)
        {
            this.x = source.x + source.width - 5;
            this.y = source.y + 16;
        }
        if (this.dir == -1)
        {
            this.x = source.x;
            this.y = source.y + 16;
        }
    }
    Bullet.prototype.update = function()
    {
        if (this.dir == 1) this.x += 8;
        if (this.dir == -1) this.x -= 8;

        for (var i in game.enemies)
        {
            checkCollisions(this, game.enemies[i]);
        }
        // Check if bullet leaves the viewport
        if (this.x < game.viewX * 32 || this.x > (game.viewX + game.tilesX) * 32)
        {
            removeFromList(game.bullets, this);
        }
    }
    Bullet.prototype.draw = function()
    {
        // bullet flipping uses orientation of the player
        var posX = game.player.scale == 1 ? this.x : (this.x + this.width) * -1;
        game.ctx.scale(game.player.scale, 1);
        game.ctx.drawImage(gameData.getGfx("bullet"), posX, this.y);
    }

```

I handle removing with this function:

```
    function removeFromList(list, object)
    {
        for (i in list)
        {
            if (object == list[i])
            {
                list.splice(i, 1);
                break;
            }
        }
    }

```

And finally, in the main game loop I have this:

```
for (var i in game.bullets)
{
    game.bullets[i].update();
    game.bullets[i].draw();
}

```

I have tried adding `if (game.bullets.length > 0)` to the main game loop before the above draw&update calls, but I still get the same error.

# Answer
As far as 1) you'll need to use a toggle state. Fire ONLY if the user did not click the previous tick, and is registered as clicking this tick. This can be thought of as the rising edge of the click state.

```
                 here should the fire logic be called
                 ^
    clicked       ___
not clicked   ___|

```

For 2) it seems that your update() causes the item to be removed from the list. The easiest fix is to draw() before you update().

---

I'm new here so I did not realise I could edit, so here it is:

As for 2 in pseudocode:

Assuming you have two booleans: isFiring, wasFiring update as such:

isFiring = isPlayerFiring(); //whatever method you use if (isFiring && !wasFiring) { //do fire logic //will only be true exactly once each fire press } wasFiring = isFiring;
> 6 votes

# Answer
Your problem with removing bullets from the list while iterating the list is a common one. It happens in many languages (not just Javascript).

If you want to remove an object from the list while you're iterating it - don't.

Instead, set a flag (I normally use "dead") to say that this object is "dead". Then have some code which checks the "dead" flags separately.

If it's an indexed container (e.g. Javascript array) you will probably want to iterate *backwards* through the list, so you can remove elements without the remaining elements changing their index.

So it'll look like this pseudocode:

```
for i in game.bullets {
  game.bullets[i].update(); // sets dead flag if bullet collides, leaves the screen, etc.
}

for (i=game.bullets.length -1; i >=0; i --) {
  var bullet = game.bullets[i];
  if (bullet.dead) {
    removeFromListByIndex(game.bullets, i);
  }
}

```
> 3 votes

# Answer
## The keypress issue

Apart from solving it manually which is already brilliantly answered, I recommend the jquery.hotkeys library, as it will also help with other game-related keyboard handling.

## The undefined issue

There are at least two issues with the last part, the first is the already noted one by AlexanderBrevig that you're removing bullets in update and then trying to call draw() on a removed bullet. The second is that you're using the for...in enumeration construct for iterating an array, which really should only be used to enumerate property names on objects¹.

So use a for-loop instead, like this:

```
for (var i = 0; i < game.bullets.length; i++)
{
     game.bullets[i].draw();
     game.bullets[i].update(); // only remove bullets at the end as AlexanderBrevig wrote
}

```

This will check the bullets.length on each iteration, so if you remove a bullet the length will change and the iteration will stop when needed.

## An unexpected problem

However, this still causes problems that might not be easy to notice or even cause any obvious trouble in a game loop: now when a bullet is removed and the array shrinks, the next bullet gets the deleted bullet's index and will never get its draw or update function called during that game tick.

One common solution is to iterate backwards:

```
for (var i = game.bullets.length-1; i >= 0; i--)
{
     game.bullets[i].draw();
     game.bullets[i].update();
}

```

## Overdone

For further fun you could make it more robust, like say you've got 5 bullets in the array and then somehow happen to do this somewhere in the code:

```
game.bullets[325] = myBullet;

```

...you will end up with a 325 long array with mostly undefined values inbetween the first five and the 325th. So check for that.

```
for (var i = game.bullets.length-1; i >= 0; i--)
{
     if (game.bullets[i] !== undefined) {
         game.bullets[i].draw();
         game.bullets[i].update();
     }
}

```

To go further you could check that the functions are actually functions, check the draw and update call separately to keep doing update before draw and so on.

¹*Yes arrays are objects and the indices are property names, but the order of for...in enumeration may change, you might get other object properties apart from your array elements and it's also slower. See this SO question for more information.*
> 3 votes

---
Tags: javascript, html5, html-canvas, platformer
---


title: How can I get macromedia flash 5?

text:
# Question
Title: How can I get macromedia flash 5?
I was used to draw and develop Flash games in the 2000's. For me that's the best vector drawing tool for 2d games ever, better than illustrator and new flash recent versions.

Can anybody tell me how can I get my hands on the old Macromedia Flash 5?

# Answer
I think this question does not really match the gamedev.stackexchange.com rules.

However I like old Flash versions too to make some vectorial draws and I keep my old CDs (including FutureSplash Animator) so I can play with them. I am almost sure you can get an official CD with serial number on websites such ebay for few dollars.

I can see two of them for less than 5$ here at the time I am writing those lines.
> 0 votes

---
Tags: 2d, flash
---


# Question
Title: Entity Type specific updates in entity component system
I am currently familiarizing myself with the entity component paradigm.

For an example, take a collision system, that detects if entities collide and if they do let them explode.

So the collision system has to test collision based on the position component and then set the state of those entities to exploding.

But what if the "effect" (setting the state to exploding) is different for different entities? For example, a ship fades out while for an asteroid a particle system must be created. Since entities and components are only data, this must happen in some system.

The collision system could do it, but then it must switch over the entity type, which in my opinion is a cumbersome and difficult to extend solution.

So how do I trigger "entity type dependend" updates on an entity?

# Answer
First things first, I would use an event-driven system rather than one based on states. Setting a state to "exploding" is clunky and rather useless, since an explosion is a one-time event.

Secondly, you can make use of what I like to call behaviour components. These components are programmed to react to certain events, like "exploded". Adding these components to an entity allows you to easily change how the entity responds to events. In this case, you could create a *FadesOutBehaviour* component that can be customized to different event types, fade times, etc. Then, whenever an entity with that component is blown up, it will fade out. The same goes for a *SpawnsParticlesBehaviour* component.

What I would really do in this case is give entities components that would fit in "real life". For example, I would forgo creating components to enable fading or particle spawning and instead use components like *FuelTank* (I can't think of one that would work for a spaceship fading; that doesn't even make sense :P). An entity containing *FuelTank* is susceptible to catching on fire, exploding, and at the same time can keep track of how much fuel it has left. The kinds of data a *FuelTank* would store would include capacity, damage, name of the mesh it is linked to inside the model, etc. Structuring entities like this makes more sense to me.
> 6 votes

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


title: Problem with Scanner class in Java

text:
# Question
Title: Problem with Scanner class in Java
I'm pretty new here (as though to a game development).
So here's my question.
I'm trying to organize a really simple game cycle in my public static main() as follows:

```
Scanner sc = new Scanner(System.in);
        //Running the game cycle
        boolean flag=true;
        while (flag) {
            int action;
            System.out.println("Type your action please:");
            System.out.println("0: Exit app");
            try
            {
                action = sc.nextInt();

                switch (action) {
                    case 0:
                        flag=false;
                        break;
                    case 1:

                        break;
                }
            }   catch (InputMismatchException ex) {
                    System.out.println(ex.getClass() + "\n" + "Please type a correct input\n");
                    //action = sc.nextInt();
                    continue;
             }

```

What's wrong with this cycle:
I want to catch an exception when user types text instead of number, show a message, warn the user, and then continue game cycle.

But instead of that, when users types wrong data, it goes into a eternal cycle without even prompting user.
What I did wrong?

# Answer
Scanner's nextInt() skips over anything that not an int and returns the first int it finds so it doesn't trigger that exception.

See example near top of http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

What you want instead is to use next() which returns a String, and then check if this String is an integer or not.
> 0 votes

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


# Question
Title: which is better performance, using a disposable local variable or reusing a global one?
This is for an android game. Suppose I have a function that is called several times for second and do some calculations involving an arraylist (or any other complex objects for what matter). Which approach would be preffered?

local:

```
private void doStuff(){
    ArrayList<Type> XList = new ArrayList<Type>();
    // do stuff with list
}

```

global:

```
private ArrayList<Type> XList = new ArrayList<Type>();
private void doStuff(){
    XList.clear();
    // do stuff with list
}

```

# Answer
> 4 votes
If you don't need the variable / results anywhere else, use the local one.

The performance gain by saving the object creation is a) almost non existant and b) most likely offset by the call to clear().

# Answer
> 0 votes
If you need to optimize this because of performance issues which is possible since you need to create this array several times every second, use a global one. I am not sure why you would clear it? Where does the data come from? Could you not overwrite the existing data without clearing explicitly?

---
Tags: java, android
---


title: Help with Collision Resolution?

text:
# Question
Title: Help with Collision Resolution?
I'm trying to learn about physics by trying to make a simplified GTA 2 clone.

My only problem is collision resolution. Everything else works great.

I have a rigid body class and from there cars and a wheel class:

```
class RigidBody extends Entity
{
  //linear
  private Vector2D velocity = new Vector2D();
  private Vector2D forces = new Vector2D();
  private OBB2D predictionRect = new OBB2D(new Vector2D(), 1.0f, 1.0f, 0.0f);
  private float mass;
  private Vector2D deltaVec = new Vector2D();
  private Vector2D v = new Vector2D();

  //angular
  private float angularVelocity;
  private float torque;
  private float inertia;

  //graphical
  private Vector2D halfSize = new Vector2D();
  private Bitmap image;

  private Matrix mat = new Matrix();
  private float[] Vector2Ds = new float[2];
  private Vector2D tangent = new Vector2D();
  private static Vector2D worldRelVec = new Vector2D();
  private static Vector2D relWorldVec = new Vector2D();
  private static Vector2D pointVelVec = new Vector2D();

  public RigidBody()
  {
      //set these defaults so we don't get divide by zeros
      mass = 1.0f;
      inertia = 1.0f;
      setLayer(LAYER_OBJECTS);
  }

    protected void rectChanged()
    {
        if(getWorld() != null)
        {
            getWorld().updateDynamic(this);
        }
    }

  //intialize out parameters
  public void initialize(Vector2D halfSize, float mass, Bitmap bitmap)
  {
      //store physical parameters
      this.halfSize = halfSize;
      this.mass = mass;
      image = bitmap;
      inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass;

      RectF rect = new RectF();
      float scalar = 10.0f;
      rect.left = (int)-halfSize.x * scalar;
      rect.top = (int)-halfSize.y * scalar;

      rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar);
      rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar);
      setRect(rect);
      predictionRect.set(rect);

  }

  public void setLocation(Vector2D position, float angle)
  {
      getRect().set(position, getWidth(), getHeight(), angle);
      rectChanged();
  }

  public void setPredictionLocation(Vector2D position, float angle)
  {
      getPredictionRect().set(position, getWidth(), getHeight(), angle);
  }

  public void setPredictionCenter(Vector2D center)
  {
      getPredictionRect().moveTo(center);
  }

  public void setPredictionAngle(float angle)
  {
      predictionRect.setAngle(angle);
  }

  public Vector2D getPosition()
  {
      return getRect().getCenter();
  }

  public OBB2D getPredictionRect()
  {
      return predictionRect;
  }

  @Override
  public void update(float timeStep)
  {
      doUpdate(false,timeStep);
  }

  public void doUpdate(boolean prediction, float timeStep)
  {
      //integrate physics
      //linear
      Vector2D acceleration = Vector2D.scalarDivide(forces, mass);
      if(prediction)
      {
           Vector2D velocity = Vector2D.add(this.velocity, Vector2D.scalarMultiply(acceleration, timeStep));
              Vector2D c = getRect().getCenter();
              c = Vector2D.add(getRect().getCenter(), Vector2D.scalarMultiply(velocity , timeStep));
              setPredictionCenter(c);
              //forces = new Vector2D(0,0); //clear forces
      }
      else
      {
          velocity.x += (acceleration.x * timeStep);
          velocity.y += (acceleration.y * timeStep);
            //velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep));
              Vector2D c = getRect().getCenter();
              v.x = getRect().getCenter().getX() + (velocity.x * timeStep);
              v.y = getRect().getCenter().getY() + (velocity.y * timeStep);
              deltaVec.x = v.x - c.x;
              deltaVec.y = v.y - c.y;
              deltaVec.normalize();
              setCenter(v.x, v.y);
              forces.x = 0; //clear forces
              forces.y = 0;
      }

      //angular
      float angAcc = torque / inertia;
      if(prediction)
      {
         float angularVelocity = this.angularVelocity + angAcc * timeStep;
         setPredictionAngle(getAngle() +  angularVelocity * timeStep);
         //torque = 0; //clear torque
      }
      else
      {
          angularVelocity += angAcc * timeStep;
          setAngle(getAngle() +  angularVelocity * timeStep);
          torque = 0; //clear torque
      }

  }

  public void updatePrediction(float timeStep)
  {
      doUpdate(true, timeStep);
  }

  //take a relative Vector2D and make it a world Vector2D
  public Vector2D relativeToWorld(Vector2D relative)
  {
      mat.reset();

      Vector2Ds[0] = relative.x;
      Vector2Ds[1] = relative.y;

      mat.postRotate(JMath.radToDeg(getAngle()));
      mat.mapVectors(Vector2Ds);

      relWorldVec.x = Vector2Ds[0];
      relWorldVec.y = Vector2Ds[1];
      return new Vector2D(Vector2Ds[0], Vector2Ds[1]);
  }

  //take a world Vector2D and make it a relative Vector2D
  public Vector2D worldToRelative(Vector2D world)
  {
      mat.reset();

      Vector2Ds[0] = world.x;
      Vector2Ds[1] = world.y;

      mat.postRotate(JMath.radToDeg(-getAngle()));
      mat.mapVectors(Vector2Ds);

      return new Vector2D(Vector2Ds[0], Vector2Ds[1]);
  }

  //velocity of a point on body
  public Vector2D pointVelocity(Vector2D worldOffset)
  {
      tangent.x = -worldOffset.y;
      tangent.y = worldOffset.x;
      return Vector2D.add( Vector2D.scalarMultiply(tangent, angularVelocity) , velocity);
  }

  public void applyForce(Vector2D worldForce, Vector2D worldOffset)
  {
      //add linear force
      forces.x += worldForce.x;
      forces.y += worldForce.y;
      //add associated torque
      torque += Vector2D.cross(worldOffset, worldForce);
  }

  @Override
  public void draw( GraphicsContext c)
  {
      c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y,
              getWidth(), getHeight(), getAngle());
  }

    public Vector2D getVelocity()
    {
        return velocity;
    }

    public void setVelocity(Vector2D velocity)
    {
        this.velocity = velocity;
    }

    public Vector2D getDeltaVec()
    {
        return deltaVec;
    }

}

Vehicle

public class Wheel
{
    private Vector2D forwardVec;
    private Vector2D sideVec;
    private float wheelTorque;
    private float wheelSpeed;
    private float wheelInertia;
    private float wheelRadius;
    private Vector2D position = new Vector2D();

    public Wheel(Vector2D position, float radius)
    {
        this.position = position;
        setSteeringAngle(0);
        wheelSpeed = 0;
        wheelRadius = radius;
        wheelInertia = (radius * radius) * 1.1f;
    }

    public void setSteeringAngle(float newAngle)
    {
            Matrix mat = new Matrix();

            float []vecArray = new float[4];
            //forward Vector
            vecArray[0] = 0;
            vecArray[1] = 1;
            //side Vector
            vecArray[2] = -1;
            vecArray[3] = 0;

            mat.postRotate(newAngle / (float)Math.PI * 180.0f);
            mat.mapVectors(vecArray);

            forwardVec = new Vector2D(vecArray[0], vecArray[1]);
            sideVec = new Vector2D(vecArray[2], vecArray[3]);
    }

    public void addTransmissionTorque(float newValue)
    {
        wheelTorque += newValue;
    }

    public float getWheelSpeed()
    {
        return wheelSpeed;
    }

    public Vector2D getAnchorPoint()
    {
        return position;
    }

    public Vector2D calculateForce(Vector2D relativeGroundSpeed, float timeStep, boolean prediction)
    {
        //calculate speed of tire patch at ground
        Vector2D patchSpeed = Vector2D.scalarMultiply(Vector2D.scalarMultiply(
                Vector2D.negative(forwardVec), wheelSpeed), wheelRadius);

        //get velocity difference between ground and patch
        Vector2D velDifference = Vector2D.add(relativeGroundSpeed , patchSpeed);

        //project ground speed onto side axis
        Float forwardMag = new Float(0.0f);
        Vector2D sideVel = velDifference.project(sideVec);
        Vector2D forwardVel = velDifference.project(forwardVec, forwardMag);

        //calculate super fake friction forces
        //calculate response force
        Vector2D responseForce = Vector2D.scalarMultiply(Vector2D.negative(sideVel), 2.0f);
        responseForce =  Vector2D.subtract(responseForce, forwardVel);

        float topSpeed = 500.0f;

        //calculate torque on wheel
        wheelTorque += forwardMag * wheelRadius;

        //integrate total torque into wheel
        wheelSpeed += wheelTorque / wheelInertia * timeStep;

        //top speed limit (kind of a hack)
        if(wheelSpeed > topSpeed)
        {
            wheelSpeed = topSpeed;
        }

        //clear our transmission torque accumulator
        wheelTorque = 0;

        //return force acting on body
        return responseForce;
    }

    public void setTransmissionTorque(float newValue)
    {
        wheelTorque = newValue;
    }

    public float getTransmissionTourque()
    {
        return wheelTorque;
    }

    public void setWheelSpeed(float speed)
    {
        wheelSpeed = speed;
    }
}

//our vehicle object
public class Vehicle extends RigidBody
{

    private Wheel [] wheels = new Wheel[4];
    private boolean throttled = false;

    public void initialize(Vector2D halfSize, float mass, Bitmap bitmap)
    {
        //front wheels
        wheels[0] = new Wheel(new Vector2D(halfSize.x, halfSize.y), 0.45f);
        wheels[1] = new Wheel(new Vector2D(-halfSize.x, halfSize.y), 0.45f);

        //rear wheels
        wheels[2] = new Wheel(new Vector2D(halfSize.x, -halfSize.y), 0.75f);
        wheels[3] = new Wheel(new Vector2D(-halfSize.x, -halfSize.y), 0.75f);

        super.initialize(halfSize, mass, bitmap);
    }

    public void setSteering(float steering)
    {
        float steeringLock = 0.13f;

        //apply steering angle to front wheels
        wheels[0].setSteeringAngle(steering * steeringLock);
        wheels[1].setSteeringAngle(steering * steeringLock);

    }

    public void setThrottle(float throttle, boolean allWheel)
    {
        float torque = 85.0f;
        throttled = true;

        //apply transmission torque to back wheels
        if (allWheel)
        {
            wheels[0].addTransmissionTorque(throttle * torque);
            wheels[1].addTransmissionTorque(throttle * torque);
        }

        wheels[2].addTransmissionTorque(throttle * torque);
        wheels[3].addTransmissionTorque(throttle * torque);
    }

    public void setBrakes(float brakes)
    {
        float brakeTorque = 15.0f;

        //apply brake torque opposing wheel vel
        for (Wheel wheel : wheels)
        {
            float wheelVel = wheel.getWheelSpeed();
            wheel.addTransmissionTorque(-wheelVel * brakeTorque * brakes);
        }
    }

    public void doUpdate(float timeStep, boolean prediction)
    {
        for (Wheel wheel : wheels)
        {
            float wheelVel = wheel.getWheelSpeed();

            //apply negative force to naturally slow down car
            if(!throttled && !prediction)
            wheel.addTransmissionTorque(-wheelVel * 0.11f);

            Vector2D worldWheelOffset = relativeToWorld(wheel.getAnchorPoint());
            Vector2D worldGroundVel = pointVelocity(worldWheelOffset);
            Vector2D relativeGroundSpeed = worldToRelative(worldGroundVel);
            Vector2D relativeResponseForce = wheel.calculateForce(relativeGroundSpeed, timeStep,prediction);
            Vector2D worldResponseForce = relativeToWorld(relativeResponseForce);

            applyForce(worldResponseForce, worldWheelOffset);
        }

        //no throttling yet this frame
        throttled = false;

        if(prediction)
        {
            super.updatePrediction(timeStep);
        }
        else
        {
            super.update(timeStep);
        }

    }

    @Override
    public void update(float timeStep)
    {
        doUpdate(timeStep,false);
    }

    public void updatePrediction(float timeStep)
    {
        doUpdate(timeStep,true);
    }

    public void inverseThrottle()
    {
        float scalar = 0.2f;
        for(Wheel wheel : wheels)
        {
            wheel.setTransmissionTorque(-wheel.getTransmissionTourque() * scalar);
            wheel.setWheelSpeed(-wheel.getWheelSpeed() * 0.1f);
        }
    }
}

```

And my big hack collision resolution:

```
private void update()
    {

        camera.setPosition((vehicle.getPosition().x * camera.getScale()) - ((getWidth() ) / 2.0f),
                (vehicle.getPosition().y * camera.getScale()) - ((getHeight() ) / 2.0f));

        //camera.move(input.getAnalogStick().getStickValueX() * 15.0f, input.getAnalogStick().getStickValueY() * 15.0f);
        if(input.isPressed(ControlButton.BUTTON_GAS))
        {
            vehicle.setThrottle(1.0f, false);
        }

        if(input.isPressed(ControlButton.BUTTON_STEAL_CAR))
        {
            vehicle.setThrottle(-1.0f, false);
        }

        if(input.isPressed(ControlButton.BUTTON_BRAKE))
        {
            vehicle.setBrakes(1.0f);
        }

        vehicle.setSteering(input.getAnalogStick().getStickValueX());
        //vehicle.update(16.6666666f / 1000.0f);

        boolean colided = false;

        vehicle.updatePrediction(16.66666f / 1000.0f);

        List<Entity> buildings = world.queryStaticSolid(vehicle,vehicle.getPredictionRect());

        if(buildings.size() > 0)
        {
            colided = true;
        }

        if(!colided)
        {
            vehicle.update(16.66f / 1000.0f);
        }
        else
        {
            Vector2D delta = vehicle.getDeltaVec();
            vehicle.setVelocity(Vector2D.negative(vehicle.getVelocity().multiply(0.2f)).
                    add(delta.multiply(-1.0f)));
            vehicle.inverseThrottle();
        }

    }

```

Here is OBB

```
public class OBB2D
{

    // Corners of the box, where 0 is the lower left.
   private  Vector2D corner[] = new Vector2D[4];

   private Vector2D center = new Vector2D();
   private Vector2D extents = new Vector2D();

   private RectF boundingRect = new RectF();
   private float angle;

    //Two edges of the box extended away from corner[0].
   private  Vector2D axis[] = new Vector2D[2];

   private double origin[] = new double[2];

   public OBB2D(Vector2D center, float w, float h, float angle)
    {
       set(center,w,h,angle);
    }

   public OBB2D(float left, float top, float width, float height)
    {
       set(new Vector2D(left + (width / 2), top + (height / 2)),width,height,0.0f);
   }

   public void set(Vector2D center,float w, float h,float angle)
   {
         Vector2D X = new Vector2D( (float)Math.cos(angle), (float)Math.sin(angle));
           Vector2D Y = new Vector2D((float)-Math.sin(angle), (float)Math.cos(angle));

           X = X.multiply( w / 2);
           Y = Y.multiply( h / 2);

           corner[0] = center.subtract(X).subtract(Y);
           corner[1] = center.add(X).subtract(Y);
           corner[2] = center.add(X).add(Y);
           corner[3] = center.subtract(X).add(Y);

           computeAxes();
           extents.x = w / 2;
           extents.y = h / 2;
           computeDimensions(center,angle);
   }

   private void computeDimensions(Vector2D center,float angle)
   {
       this.center.x = center.x;
       this.center.y = center.y;
       this.angle = angle;

       boundingRect.left = Math.min(Math.min(corner[0].x, corner[3].x), Math.min(corner[1].x, corner[2].x));
       boundingRect.top = Math.min(Math.min(corner[0].y, corner[1].y),Math.min(corner[2].y, corner[3].y));
       boundingRect.right = Math.max(Math.max(corner[1].x, corner[2].x), Math.max(corner[0].x, corner[3].x));
       boundingRect.bottom = Math.max(Math.max(corner[2].y, corner[3].y),Math.max(corner[0].y, corner[1].y));
   }

   public void set(RectF rect)
   {
       set(new Vector2D(rect.centerX(),rect.centerY()),rect.width(),rect.height(),0.0f);
   }

    // Returns true if other overlaps one dimension of this.
    private boolean overlaps1Way(OBB2D other)
    {
        for (int a = 0; a < axis.length; ++a) {

            double t = other.corner[0].dot(axis[a]);

            // Find the extent of box 2 on axis a
            double tMin = t;
            double tMax = t;

            for (int c = 1; c < corner.length; ++c) {
                t = other.corner[c].dot(axis[a]);

                if (t < tMin) {
                    tMin = t;
                } else if (t > tMax) {
                    tMax = t;
                }
            }

            // We have to subtract off the origin

            // See if [tMin, tMax] intersects [0, 1]
            if ((tMin > 1 + origin[a]) || (tMax < origin[a])) {
                // There was no intersection along this dimension;
                // the boxes cannot possibly overlap.
                return false;
            }
        }

        // There was no dimension along which there is no intersection.
        // Therefore the boxes overlap.
        return true;
    }

    //Updates the axes after the corners move.  Assumes the
    //corners actually form a rectangle.
    private void computeAxes()
    {
        axis[0] = corner[1].subtract(corner[0]);
        axis[1] = corner[3].subtract(corner[0]);

        // Make the length of each axis 1/edge length so we know any
        // dot product must be less than 1 to fall within the edge.

        for (int a = 0; a < axis.length; ++a) {
            axis[a] = axis[a].divide((axis[a].length() * axis[a].length()));
            origin[a] = corner[0].dot(axis[a]);
        }
    }

    public void moveTo(Vector2D center)
    {
        Vector2D centroid = (corner[0].add(corner[1]).add(corner[2]).add(corner[3])).divide(4.0f);

        Vector2D translation = center.subtract(centroid);

        for (int c = 0; c < 4; ++c)
        {
            corner[c] = corner[c].add(translation);
        }

        computeAxes();
        computeDimensions(center,angle);
    }

    // Returns true if the intersection of the boxes is non-empty.
    public boolean overlaps(OBB2D other)
    {
        if(right() < other.left())
        {
            return false;
        }

        if(bottom() < other.top())
        {
            return false;
        }

        if(left() > other.right())
        {
            return false;
        }

        if(top() > other.bottom())
        {
            return false;
        }

        if(other.getAngle() == 0.0f && getAngle() == 0.0f)
        {
            return true;
        }

        return overlaps1Way(other) && other.overlaps1Way(this);
    }

    public Vector2D getCenter()
    {
        return center;
    }

    public float getWidth()
    {
        return extents.x * 2;
    }

    public float getHeight()
    {
        return extents.y * 2;
    }

    public void setAngle(float angle)
    {
        set(center,getWidth(),getHeight(),angle);
    }

    public float getAngle()
    {
        return angle;
    }

    public void setSize(float w,float h)
    {
        set(center,w,h,angle);
    }

    public float left()
    {
        return boundingRect.left;
    }

    public float right()
    {
        return boundingRect.right;
    }

    public float bottom()
    {
        return boundingRect.bottom;
    }

    public float top()
    {
        return boundingRect.top;
    }

    public RectF getBoundingRect()
    {
        return boundingRect;
    }

    public boolean overlaps(float left, float top, float right, float bottom)
    {
        if(right() < left)
        {
            return false;
        }

        if(bottom() < top)
        {
            return false;
        }

        if(left() > right)
        {
            return false;
        }

        if(top() > bottom)
        {
            return false;
        }

        return true;
    }

};

```

What I do is when I predict a hit on the car, I force it back. It does not work that well and seems like a bad idea.

What could I do to have more proper collision resolution. Such that if I hit a wall I will never get stuck in it and if I hit the side of a wall I can steer my way out of it.

Thanks

I found this nice ppt. It talks about pulling objects apart and calculating new velocities. How could I calc new velocities in my case?

http://www.google.ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CC8QFjAB&url=http%3A%2F%2Fcoitweb.uncc.edu%2F~tbarnes2%2FGameDesignFall05%2FSlides%2FCh4.2-CollDet.ppt&ei=x4ucULy5M6-N0QGRy4D4Cg&usg=AFQjCNG7FVDXWRdLv8\_-T5qnFyYld53cTQ&cad=rja

# Answer
(TLDR the code)

> "What could I do to have more proper collision resolution. Such that if I hit a wall I will never get stuck in it and if I hit the side of a wall I can steer my way out of it."

Try to move the objects and separate them slightly in the direction normal to the collision.
> 3 votes

---
Tags: java, physics, algorithm, collision-resolution
---


# Question
Title: Ruby Vs. C# - Better for Game Programming
I have seen some games made in C#, such as using the XNA. I saw some games made in Ruby by using the RGSS1-3 API as well. I just can't decide on my own which would be easier to learn and apply for game programming. I want your opinion on which is better to make games with, is it Ruby or C#? What are the advantages and disadvantages of each?

# Answer
> 3 votes
Besides the very valid point Liosan makes about being able to make Unity games, Another really nifty advantage of C# is the ability to use the MonoGame framework to (as they put it) *"...allow XNA developers on Xbox 360, Windows & Windows Phone to port their games to the iOS, Android, Mac OS X, Linux and Windows 8 Metro. PlayStation Mobile development is currently in progress."*

---
Tags: c#, ruby
---


# Question
Title: HLSL Pixel Shader that does palette swap
I have implemented a simple pixel shader which can replace a particular colour in a sprite with another colour.

It looks something like this:

```
sampler input : register(s0);
float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 colour = tex2D(input, coords);
    if(colour.r == sourceColours[0].r &&
    colour.g == sourceColours[0].g &&
    colour.b == sourceColours[0].b) return targetColours[0];
    return colour;
}

```

What I would like to do is have the function take in 2 textures, a default table, and a lookup table (both same dimensions). Grab the current pixel, and find the location XY (coords) of the matching RGB in the default table, and then substitute it with the colour found in the lookup table at XY.

I have figured how to pass the Textures from C# into the function, but I am not sure how to find the coords in the default table by matching the colour.

Could someone kindly assist?

Thanks in advance.

# Answer
> 1 votes
Hmm, I have just registered my account, but I can't access my original post. Can any moderator help?

Anyway, I was using 2D array so that I can store different "palettes" and swap between them. I will simplify the solution so that it uses a 1x4 and see if I can "toggle" between the 4 pixels with hardcoded values.

# Answer
> 0 votes
You should not use loops...

Have you consider using a palette, and use one color channel of the primary texture as index?

You can use the red channel as index, and sample to a Texture1D where you store your palette colors

---
Tags: c#, shaders, hlsl, pixel, palette
---


# Question
Title: Need material for character anatomy in a 2D game. Spartan Like, See Picture
I'm creating my art for an 2d based IOS game. I know some basic anatomy as you can see by the picture but I have no idea how I will make draw the pics for animation of the character walking, attacking with his sword and protecting himself with shield.

Is there any anatomy reference for 2d game out there, book or anything else?

for your information, I did try to find but all of stuff I found are very amateur and incomplete

The picture was my attempt of creating a example of the character walking, which I'm not happy with

please help, thanks

Update:

Since I am in a hurry I decided I would copy the anatomy from other 2d games, it is not that clean but at least I wanna be able to start it. The question is still open.

# Answer
Would have done the same. You could as well try some kind of "poor guy's Motion capturing" by recording yourself doing the specific moves or by using some 3d modelling software to do it. The latter might be easier in case you want a deformed character.

Create key frames using still Images (3-4 should be enough; maybe even only 2 depending on what you want) and then layering to draw your character on top.
> 2 votes

# Answer
You should be looking at classical art and animation references. The basics are the same, there's nothing special about games or "2d games" that set them apart in terms of the art.

A great reference for animation is Preston Blair's book on cartoon animation:

http://www.scribd.com/doc/7582342/Preston-Blair-Cartoon-Animation

You can also search youtube for videos of motion capture or just people performing the actions you want to animate, and use those as reference.
> 2 votes

---
Tags: 2d, platformer
---


# Question
Title: Re-create 2D side-on wave effect from Worms game
I'm trying to recreate the waves/water effect from Worms ( see here http://youtu.be/S6lrRqst9Z4?t=31s ) From what I understand its not actually a sprite, its procedurally generated by something like a sin wave.

Has anyone created something like this before? or any idea how I would go about it?

# Answer
Yes, you are right, this 2D water effect can be simulated using math sine function :

```
wave = sin(phase + t * frequency) * amplitude

```
* `phase` is a constant, put whatever you want.
* set `t` to horizontal position of pixel/vertex you are processing : `t = x;`
* change `amplitude` over the time (that will make the waves moving up and down) :

`amplitude = sin(t * wave_speed) * wave_height`
* combine several waves to get a more relastic effect :

`wave_final = wave0 + wave1 + ...` .

For each wave, change some parameters a little bit (eg: phase, frequency,...).

Here is a quick example i made, using only two waves :

http://glslsandbox.com/e#4988.0 (require recent browser and WebGL enabled)

NOTE : this is a shader, but doing this using 2D primitives is the same approach .

EDIT : you dont specify any framework or 2d rendering system, but here is how it could be rendered using polygons / triangle strips :
> 14 votes

---
Tags: 2d, mathematics, special-effects, graphics-design
---


# Question
Title: Collision checking problem on a Tiled map
I'm working on a pacman styled dungeon crawler, using the free oryx sprites. I've created the map using Tiled, separating the floor, walls and treasure in three different layers. After importing the map in libGDX, it renders fine. I also added the player character, for now it just moves into one direction, the player cannot control it yet. I wanted to add collision and I was planning to do this by checking if the player's new position is on a wall tile. Therefore as you can see in the following code snippet, I get the tile type of the appropriate tile and if it is not zero (since on that layer there is nothing except the wall tile) it is a collision and the player cannot move further:

```
final Vector2 newPos = charController.move(warrior.getX(), warrior.getY());
if(!collided(newPos)) {
    warrior.setPosition(newPos.x, newPos.y);
    warrior.flip(charController.flipX(), charController.flipY());
}

```

\[..\]

```
private boolean collided(Vector2 newPos) {
    int row = (int) Math.floor((newPos.x / 32));
    int col = (int) Math.floor((newPos.y / 32));

    int tileType = tiledMap.layers.get(1).tiles[row][col];
    if (tileType == 0) {
        return false;
    }

    return true;
}

```

The character only moves one tile with this code:

If I reduce the `col` value by two it two more tiles. I think the problem will be around indexing, but I'm totally confused because the zero in the coordinate system of libGDX is in the bottom left corner of the screen, and I don't know the `tiles` array's indexing is similair or not. The size of the map is 19x21 tiles and looks like the following (the starting position of the player is marked with blue:

# Answer
> 1 votes
This looks suspect,

```
int row = (int) Math.floor((newPos.x / 32));
int col = (int) Math.floor((newPos.y / 32));

```

row would make more sense if you used newPos.y and not newPos.x, so try swapping them round like I have done below

```
int col = (int) Math.floor((newPos.x / 32));
int row = (int) Math.floor((newPos.y / 32));

```

Edit: Try the following, flip the y by map height which you say is 21, given it starts at 0 and not 1, then its 20-row and not 21-row

```
int tileType = tiledMap.layers.get(1).tiles[20-row][col];

```

If that doesn't work then you need to do a for next loop for all rows and cols and print the map value out on screen. Once you see your patterns of 0 and 1 on screen you will soon see where it is wrong.

# Answer
> 1 votes
If your character is only moving one block, then it looks like they are actually moving to the right instead of the left, as there is only one block to move to on the right. Make sure all your coordinates are the same.

The fact that you do `warrior.flip(charController.flipX(), charController.flipY());` makes seems to confirm that. Try flipping it before doing the collision check and see if that helps.

EDIT: Coincidently I am also making a game based on pacman, so I will give you a hint, if you are moving your character on a pixel basis, you are going to need to add some extra code to your collision check so they he isn't halfway in a wall. This will depend on the direction your character is moving, since you are just doing right now, I will use that. You want to make sure that the left side of the sprite, not necessarily the characters position, isn't impacting the wall.

EDIT: Did you try flipping the newPos before calling collided?

i.e.

```
final Vector2 newPos = charController.move(warrior.getX(), warrior.getY());
flip(newPos);
if(!collided(newPos)) {
    warrior.setPosition(newPos.x, newPos.y);
    warrior.flip(charController.flipX(), charController.flipY());
}

```

---
Tags: java, collision-detection, tiles, libgdx, tilemap
---


# Question
Title: Rotation, further I go from 0:0, the further the object positions around the origin while rotating
For some reason I am having the issue where the following code:

```
 global.spriteBatch.Draw(obj.sprite, obj.getPosition(), null, Color.White, obj.rotation, obj.center, 2f, SpriteEffects.None, 1);

```

causes the object to rotate around the origin in such a way, as though there is an offset to the position relative to its location. The calculation for the center it correct and this happens even if I set the pivot to be the location of the object. The further I get from 0:0 the larger the radius or rotation. I am not sure what is going on here because given the following tutorial

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Rotation.php

I have done the code setup correctly. Any ideas? Any help is greatly appreciated!!!

# Answer
> 1 votes
This was a bit of stupid mistake. I assumed the the origin was relative to the world when its not. The origin is the offset to the object. To get the offset, you can simply do the following:

obj.center - obj.getPosition

for the origin and it will give you your offset for your center.

---
Tags: xna, rotation
---