title: Collision Shapes Abstraction Design

text:
# Question
Title: Collision Shapes Abstraction Design
Straight to the facts.

1. I have a base CEntity class for different entities in my game:

* Static entities ( those do not move, simply props and items )
    * Dynamic entities ( these move, jump )
2. Each of these can have a different collision shape, the shapes supported are:

* CCollisionShapeAABB ( AABB )
    * CCollisionShapeBSphere ( Bounding Sphere )
    * CCollisionShapeSoup ( Polygon soup, a list of vertices/indices )
3. CEntity the base class for all entities has a member object, that is initialized later on by inheriting classes depending on their collision shape. Below, CEntityPlayer initialisation, where Player uses AABB.

> ```
> // Initialize proper Collision Shape for this Entity
> m_pCollisionShape = new CCollisionShapeAABB(pNewNode->GetSizeMinimals(),
>                                             pNewNode->GetSizeMaximals());
>
> ```

CEntity has a method that takes another entity, and performs intersection test. The intersection test depends on the type of Collision Shape entities have.

```
bool CEntity::Intersect(CEntity *pEntity)
{
    ASSERT(pEntity);

    CCollisionShape::eCollisionShapeClass _myClass  = m_pCollisionShape->GetCollisionClass();
    CCollisionShape::eCollisionShapeClass _hisClass = pEntity->GetCollision()->GetCollisionClass();

    if(_myClass == CCollisionShape::eCollisionShapeClass::COLLISION_SHAPE_CLASS_AABB)
    {
        CCollisionShapeAABB *pMyShape = static_cast<CCollisionShapeAABB*>(m_pCollisionShape);

        if(_hisClass == CCollisionShape::eCollisionShapeClass::COLLISION_SHAPE_CLASS_AABB)
        {
            return pMyShape->Collides(*static_cast<CCollisionShapeAABB*>(pEntity->GetCollision()));
        }
        else if(_hisClass == CCollisionShape::eCollisionShapeClass::COLLISION_SHAPE_CLASS_BOUNDINGSPHERE)
        {
            return pMyShape->Collides(*static_cast<CCollisionShapeBSphere*>(pEntity->GetCollision()));
        }
        else if(_hisClass == CCollisionShape::eCollisionShapeClass::COLLISION_SHAPE_CLASS_POLYGONSOUP)
        {
            return pMyShape->Collides(*static_cast<CCollisionShapeSoup*>(pEntity->GetCollision()));
        }
    }

    return false;

}

```

I can't figure out today, how should i approach this to avoid a situation, where i need to check for each individual Collision Shape type, before doing any intersection test?

Thanks v.much for any input into this!

**UPDATE**

The CCollisionShape Class is a Base class for other CCollisionShape\* classes, and it looks as follows.

> class CCollisionShape { public:
>
> ```
>     enum eCollisionShapeClass
>     {
>         COLLISION_SHAPE_CLASS_UNKNOWN = 0,
>         COLLISION_SHAPE_CLASS_AABB,
>         COLLISION_SHAPE_CLASS_BOUNDINGSPHERE,
>         COLLISION_SHAPE_CLASS_POLYGONSOUP,
>         COLLISION_SHAPE_CLASS_TOTAL
>     };
>
>     CCollisionShape();
>     virtual ~CCollisionShape();
>
>     const eCollisionShapeClass GetCollisionClass() const;
>
>
>     bool        Collides            (CCollisionShape *pCollisionShape);
>
>
>     virtual     bool Collides       (const class CCollisionShapeAABB& rCollisionShape) const = 0;
>     virtual     bool Collides       (const class CCollisionShapeBSphere& rCollisionShape) const = 0;
>     virtual     bool Collides       (const class CCollisionShapeSoup& rCollisionShape) const=0;
>     virtual     bool Collides       (const  CVector3& vPosition) const = 0;
>     virtual     bool Collides       (const  CFrustum& rFrustum) const = 0;
>     virtual     bool Collides       (const  CRay& rRay) const = 0;
>     virtual     int  Collides       (const  CPlane& rPlane) const = 0;
>     virtual     bool Collides       (const  CTriangle& rTriangle) const = 0;
>
> protected:
>     eCollisionShapeClass m_eCollisionClass; };
>
> ```

Now the ::Collides() method looks as follows

> bool CCollisionShape::Collides(CCollisionShape \*pCollisionShape) { // ASSERT(pCollisionShape);
>
> ```
> CCollisionShape::eCollisionShapeClass _hisClass = pCollisionShape->GetCollisionClass();
>
> if(_hisClass == CCollisionShape::eCollisionShapeClass::COLLISION_SHAPE_CLASS_AABB)
> {
>     return Collides(static_cast<CCollisionShapeAABB*>(pCollisionShape));
> }
> else if(_hisClass == CCollisionShape::eCollisionShapeClass::COLLISION_SHAPE_CLASS_BOUNDINGSPHERE)
> {
>     return Collides(static_cast<CCollisionShapeBSphere*>(pCollisionShape));
> }
> else if(_hisClass == CCollisionShape::eCollisionShapeClass::COLLISION_SHAPE_CLASS_POLYGONSOUP)
> {
>     return Collides(static_cast<CCollisionShapeSoup*>(pCollisionShape));
> }
>
> return false; }
>
> ```

And collision testing from the Game goes with:

> CEntity \*pPlayer = GetEntity("Player"); CEntity \*pSector = GetEntity("Sector");
>
> ```
> CCollisionShape *pCA = pPlayer->GetCollision();
> CCollisionShape *pCB = pSector->GetCollision();
>
> if(pCA->Collides(pCB))
> {
>     exit(0);
> }
>
> ```

# Answer
> 3 votes
First of all, `CEntity` should not have an `Intersect` method *at all*. This is simply not its functionality, in your case you are going towards a god `CEntity` class that knows about everything, when you should usually prefer minimal interface.

When designing a class I always strive for these two principles;

If you ask how you should porform intersection at the entity level. Then the answer is simply you don't. The approriate way will become like this:

```
CollisionShape* shape = entity->GetCollisionShape(); //or use references.
shape->Intersect(other);

```

The intersect method will become in the CollisionShape (or even outside, but that's a different debatable subject) like this:

```
bool CCollisionShape::Intersect(CCollisionShape *otherShape)
//or as a free function
bool Intersect(CCollisionShape *shape, CCollisionShape *otherShape)

```

In your current approach you are losing all type safety for no good reason. And also exposing functionality to CEntity that it shouldn't know about.

My second point is what you are doing right now is actually simulate dynamic dispatch by checking for the type each time, this is usually a bad design, two simple reasons I can think off are:

* If you want to add new type you will always need to remember to add it to the type checking.
* That it's error prone, and your static case, while faster could cause hard to find bugs on release if you are not careful enough.

The cleaner way to do this is to actually use polymorphism for your collision shapes, override `Intersect` for each collision shape, and let the language run time figure out the type for you. This will eliminate the type checking if statement.

Now what are the gains you **might** take from your current dynamic dispatch simulation?

* You are not actually performing dynamic dispatch, hence no double indirection.
* Which also means your ccollision methods *could* be inlined.

But remeber that the above points are not valid unless you really profile your application and find that they cause a bottleneck. Otherwise *always* take the cleaner design.

---
Tags: c++, collision-detection, architecture, polymorphism
---


# Question
Title: Ward model implementation: specular component too weak
I'm trying to implement the Ward shading model, the anisotropic, computationally efficient version:

This is how I made it:

```
float alphaX=0.5, alphaY=0.5; // asinotropic roughness
float minFloat= 1.e-6;

vec4 Ward(vec3 L, vec3 N, vec3 V)
{
    vec3 H= normalize(L+V);
    float NdotL= max(dot(N,L),0.0);
    float NdotV= max(dot(N,V),0.0);

    vec3 e= vec3(1.0,0.0,0.0);
    vec3 T= normalize(cross(N,e));
    vec3 B= normalize(cross(N,T));
    float HdotT= max(dot(H,T),0.0);
    float HdotB= max(dot(H,B),0.0);
    float HdotN= max(dot(H,N),0.0);

    float beta= -2.0 * ( pow(HdotN/alphaX, 2.0) + pow(HdotB/alphaY,2.0) ) / (1.0 + HdotN);
    float den= max(minFloat, 4.0 * pi * alphaX * alphaY * sqrt(NdotL * NdotV) );
    vec4 specular= Ps * 1.0/den * exp(beta);
    return (Pd + specular) * NdotL;
}

```

But I get a result similar to a lambertian surface or Oren-Nayar model, where the specular component is absent:

# Answer
> 2 votes
The problem was solved by just changing the `e` vector to `(0,0,-1)`. I also needed to clamp the returned color:

```
return clamp((Pd + specular) * NdotL, 0.0, 1.0);

```

Result:

# Answer
> 0 votes
Your alpha values are too high. You have them both set to 0.5, which represents a very rough surface, which will have a very broad and diffuse specular highlight. Try setting them to something like 0.01, and you should get a smaller, hotter highlight.

The alpha values in the Ward distribution work similarly to the "m" value in the Beckmann distribution - they control the typical slope of microfacets, so small values correspond to smooth, glossy surfaces.

---
Tags: glsl, fragment-shader, webgl
---


# Question
Title: Flip DDS Texture without original source image for OpenGL
I'm wondering if there's a converter for DDS textures after they've been created. We don't have access to the original source images and we would like to avoid changing our shaders, as I'm told it's less efficient to flip them during runtime. Also we don't want the added load time of flipping them. Does anything like that exist? I couldn't find it if there is...

# Answer
> 2 votes
Not sure how I missed this one originally, but NVidia has the DDS Utilities Legacy Texture Tool - https://developer.nvidia.com/legacy-texture-tools.

Specify the -flip option and walla! good to go...

EDIT: the only downside to this is that it tends to increase the size of textures unnecessarily, changing some from DXT1 to DXT5, and there doesn't seem to be a way to match the output texture type to the input texture type. So it looks like I might have to write a tool to read the type and pass that through the command line...

# Answer
> 1 votes
If you have Adobe Photoshop, you could use the Nvidia Texture Tools for Adobe Photoshop: https://developer.nvidia.com/nvidia-texture-tools-adobe-photoshop

It gives you a bit more control over your textures, and you can even edit dds textures this way.

---
Tags: opengl, dds
---


# Question
Title: What is the simplest way to export a bezier curve created in Blender to a text file?
I have created a `bezier curve` in `Blender`.

I'd like to export this curve to a `text file`. What I need is :

Control point + handles, three points in total.

Example :

```
{{ 2.3333,4.3942, 55.333 }, { 0.3234, 2.4234, 4.0332 }, { 2.534, 6.S234, 12.0332 }}

```

I have tried to export the scene in `Collada` format but it doesn't seems to include curves information.

What is the easiest / simplest way to export this curve to some readable text file format ?

# Answer
There are scripts available that do this. Though they may be a bit out of date. Perhaps not the simplest method, but you can write your own python script to export them. Using Blender scripting you can enumerate the objects in the scene and then enumerate through all the curves of a particular bezier curve.
> 3 votes

# Answer
Try this:

```
import bpy
myCurve = bpy.data.curves[0] # here your curve
spline= myCurve.splines[0] # maybe you need a loop if more than 1 spline

print("\n======================")
for x in range(len(spline.bezier_points)):
    print("Point " + str(x)
        ,spline.bezier_points[x].co
        ,spline.bezier_points[x].handle_left
        ,spline.bezier_points[x].handle_right)

```
> 4 votes

# Answer
For anyone interested, here is revelant code :

```
ob = bpy.context.object # active object

# iterate over points of the curve's first spline
file = open('foo.txt', 'w')
for p in ob.data.splines.active.bezier_points:
    file.write("%.3f, %.3f, %.3f" % p.co.x, p.co.y, p.co.z)
    file.write("%.3f, %.3f, %.3f" % p.handle_left.x, p.handle_left.y, p.handle_left.z)
    file.write("%.3f, %.3f, %.3f" % p.handle_right.x, p.handle_right.y,p.handle_right.z)
fclose(f)

```
> 0 votes

---
Tags: blender, collada, beziers, export
---


title: Triangulating a point mesh at runtime

text:
# Question
Title: Triangulating a point mesh at runtime
I'm familiar with various methods of triangulation (eg Delaunay), but since I have hundreds of thousands of regularly spaced points that may need to be revisited like this on each physics frame, I'm hoping that there's a more efficient way to do this.

What I need to do is, given a series of points like this:

locate the triangles and perimeter. While I haven't show it in this image, it should be possible to form holes in the mesh where there are points missing inside the blue perimeter shown below. Still, I do need to find *all the interior perimeters*.

or, if it would be faster

My current plan is to use Delaunay triangulation to build the mesh, not merging the triangles at all, and then starting from an arbitrary point, select points which meet criteria for being an edge (being a member of less than 5 triangles?). Is there a more efficient way to do this?

# Answer
I did something like this recently, working from a raster image each frame. My steps were:

1. Read thresholded values from the image into an array.
2. Scan the array, looking for a positive value.
3. When I find one, walk the perimeter separating positive from negative space, accumulating points.
4. Once the contour is completed, invert every point inside it (so holes become positives that will get their own contours traced). And continue scanning the array.
5. Decimate the resulting contours, to eliminate points that have little impact on the shape.
6. Run a monotone triangulation algorithm on the contours (split into monotone polygons and then triangulate)

As it turns out, step 5 is the worst bottleneck in my current version - the monotone triangulation runs surprisingly fast, even with many points. By not doing the decimation step, you may already get acceptable speed even from this simple approach.

If changes to your point set are localized and incremental, you can avoid the full scan each frame and only re-scan the neighbourhood of changes.
> 2 votes

# Answer
If you store the points using a run-length-encoding e.g.

```
[num_points][num_empty][pt1][pt2][pt3]...
(algo will now increment num_empty here)
[num_points][num_empty][pt1]...

```

Then visiting the points (for physics or to compute perimeter or to generate triangles) will be O(n) where n is the number of points, *rather* than n being the size of the space.

The perimeter can be used by decoding to a bitmap the last three scan-lines, and computing the adjacency on the middle scan-line.

This becomes more expensive to remove points after the RLE structure has been built, but it is doable. You can have a tombstone point type so you can put short runs of only one or more empty points in the middle of a span, and you can in-place write a new zero\_num\_points span every time you have enough adjacent deleted points so you can easier skip over them.
> 2 votes

---
Tags: optimization, triangulation
---


# Question
Title: How can I implement a game locator or proxy server?
I have a turn-based strategy game which already has a multiplayer server/client layer that works fine on local network (where one server is set up and players connect to it).

I would like to extend this architecture to allow players to play via Internet, but I don't want to have a dedicated game server for that, especially due to performance issues. The game's AI is runs on the game server of course, and multiple games with computer players would "kill" the machine.

I would like to have some kind of "central connection point" server that does not run the game logic, state or AI but can be used by players to find servers hosted by other players. How can I implement this?

# Answer
> 3 votes
Having some kind of central "meta server" or "locator server" is pretty standard practice, and they are pretty generic and straightforward (even though entire middleware solutions, such as GameSpy, used to be popular in the early days of internet gaming).

A locator server just maintains a list of known active game servers that can accept connections, probably in a very simple database table (or entirely in-memory if you really want to be simple). Consequently:

* A game server, when it starts up, will send a message to the locator server with some basic information about itself, such as the IP and port it's running on, how many players spots are available for joining, and what the gametype (if applicable) is.
* The game server will send a "close game" message when it either fills up or is cancelled. The locator server should probably also time-out entries as well, to handle cases where the game server just crashed outright.
* A game client can then request, from the locator server , the list of all games. Often this list is refreshed from the server every few seconds while the player is on the "join a game" screen in the client.

At the bare minimum, that's all a locator server needs to do. When a player elects to join a listed game, the client can attempt a direct connection to the server using the information reported from the locator server -- you don't need to shuffle state between the two by way of the locator at all.

However, a locator server can be useful to act as a third-party in NAT punch-through (alternate explanation) scenarios as well, which does involve transferring more information between the locator as a third-party, though never full game state.

You *could* use it to pass through complete game state updates and act as a proxy, although in that case while the locator itself is still very straightforward to implement, it's potentially moving a lot more data around and that won't scale as well to a larger number of clients and servers. If that's what you're after (effectively avoiding the need for the game client and game server to ever talk directly), then you'll probably want to additionally have the locator server responsible for talking to a bunch of proxy servers you run. Each of these proxy servers exist solely to act as the intermediary for communication between a game client and server, which never talk directly. The proxies also must periodically communicate with the locator some information about how many games they are managing, for load-balancing purposes.

The game client and server still use the locator server to establish an initial connection, but the locator immediately negotiates with which proxy is least-loaded at the time and messages are sent to the game client and server to "talk to proxy 32" (or whichever). The game client and server will then use proxy 32 (or whichever) to rely communication about game state updates and so on, until the game ends.

It's quite likely your game won't be high-traffic enough to actually warrant needing a whole fleet of proxies, but if you do intend to avoid having a direct communication between the client and server for some odd reason (which seems unnecessarily complex), you should probably at least design the locator and proxying aspects of the intermediate server as separate. Just in case.

You don't want to have your game become suddenly popular, and then have your network infrastructure fall over when the surge of new players happens.

# Answer
> 0 votes
I've rethought things a little, and I am now considering having a web server which will keep the state and with every turn, this state gets updated. Therefore wouldn't be any direct connection between client and game server.

The Game server (where AI will run) will act in this architecture as another client and locator will be the primary source of the current state (lets call it Internet server).

This would be the process:

1. First player starts the multiplayer game. This creates new process "AI server" on the same machine and calls Internet server telling it that a new game is created. The direct connection between the player's app (let's call it client 1) and AI server is closed.
2. AI server and client 1 start to communicate with Internet server exclusively.
3. Every move goes through the Internet server and it updates its state. All connected clients (right now AI server and client 1) ask periodically for state update.
4. When AI player should play, the AI server simply starts sending its turns like any other client.
5. When a new client wants to play, it simply downloads the state from Internet server and list of clients is updated.

---
Tags: networking, client-server, turn-based-strategy
---


title: Create body on a sprite (box2D)

text:
# Question
Title: Create body on a sprite (box2D)
I'm quite experimented in objective C, but now i'm tried cocos2D and his features.

I need to add a body on a spritesheet (if possible on a classic 'UIImageView'), in order to detect collisions after.

Is there a way to create a box2D body, and that it suits sprite position ?

Because i wrote :

```
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    CGPoint current = myUIImageView.center;
    int accelerator = 25;
    if (current.y > 70 && current.y < 407)
    {
        current.y -= acceleration.y*accelerator;
    }
    else if (current.y <= 70)
    {
        if (acceleration.y < 0)
        {
            current.y -= acceleration.y*accelerator;
        }
    }
    else if (current.y >= 407)
    {
        if (acceleration.y > 0)
        {
            current.y -= acceleration.y*accelerator;
        }
    }
    myUIImageView.center = current;
}

```

and found some codes, but looks very hard...

Thanks for your help !

# Answer
Have you looked into CCPhysicsSprite?

Otherwise you can use the `b2body.userData` pointer to store sprite information after you've created your physics body.
> 1 votes

---
Tags: ios, box2d, cocos2d-iphone, cocos2d, objective-c
---


# Question
Title: Tracing a 2d path through multiple gravity fields
For a projectile starting at origin *O*, an initial velocity *V*, and several **stationary** planets *P\[n\]*, how would I pre-calculate and store the path it would take without actually stepping through each frame along the curve?

I have some idea of how to do this for a single gravity source (conic section, parametric curves), but how do you blend multiple forces, and thus multiple curves, together?

The idea is to give the player some idea of the trajectory their shot will take, so it doesn't need to reflect the actual path *exactly*, but the closer the better.

# Answer
> 5 votes
You step through the simulation quickly, in a `for` loop or a `while` loop depending on what the goal is. You're essentially simulating the frames in the loop with predetermined time steps, ideally with the same value as your fixed time step. Depending on how you have your game set up, this could be as easy as using your existing functions.

---
Tags: physics, projectile-physics
---


# Question
Title: Programming an Artificial Agent in Open Arena
Does anyone know source example source codes and tutorials to start writing an intelligent bot for Open Arena?

# Answer
Actual tutorials on the specific subject are sparse, but I did find a paper on a specific bot: http://www.scribd.com/doc/20585341/The-Quake-III-Arena-Bot

As well as a list of commands for a quake 3 bot: http://www.quake3world.com/q3guide/bots.html

The basic AI could be very simple, just a Finite State Machine with states for:

* hunting other bots or players
* Fighting target
* running from other bots or players when low on resources
* looking for resources when low and not engaged

Writing the logic for each state, and the entrances and exits to each is where it can go from simple "fire gun at target" to complex "aim at target at rate X while moving to cover at position Y and fire once reticule is within Z of target".
> 1 votes

# Answer
Quake 3 source code and UDK are the best examples.
> -1 votes

---
Tags: ai, quake3
---


title: Shop and Inventory System

text:
# Question
Title: Shop and Inventory System
I'm creating a JavaScript game, and I'm getting stuck. When the player obtains X amount of gold, a middle column appears (you've unlocked the shop, yay!), and when you obtain more gold than an item costs, it will appear (except special conditions where it requires more than just gold of course).

Right now, I'm stuck on the base foundation of the system, and I would like to hear some suggestions before I move on.

```
function _shop() {
    this.items = [
        {
            effect : function() { engine.player.revive(true); },
            "price" : 100,
            "name" : "Heal"
        }
    ];
}

```

The shop holds an array of item objects, some will be holdable, some will be instant use (currently working on instant use).

Now, here's how the item is called:

in my elements.js file --

```
addShopItem : function(gold) {
    console.log(engine.shop.items.length);
    for (var i = 0; i < engine.shop.items.length; i++) {
        if (engine.shop.items[i]["price"] <= gold) {
            document.getElementById("items").innerHTML += "<br />"+engine.shop.items[i].name;
        }
    }
},

```

Which is called by going raiding (irrelevant, won't post that code, it's going to change to the engine's trigger function with flags based on the item object.

Now my question is:

1. Is this a good way to handle an dynamic shop system?
2. What's the best way to link this to a player object? (My initial guess is an object `inventory` inside the parent?

# Answer
I would recommend you to look into Entity Component System architecture. This is exactly use case where it will shine. There is nice article here and very good implementation by Richard Lord called Ash Framework. It's mainly written for ActionScript (Flash), but there are already ports to other languages, Javascript included.

In the short, it would allow you to have entity for each item type and attach components on entity depending on what properties such items has. You can combine those components freely. It allows you to extend it easily later when you need something else for that item to do. Than you have system for shopping, system for fighting, system for reviving and so on. Each system is interested only in limited set of components on entities and is working with those.

I am not sure how far in development you are, if just beginning, it's really good idea go this way. Otherwise just learn and do it for the next game.

*I would post links for that framework, but my reputation is rather low, so just google Ash Framework*
> 1 votes

# Answer
Since I don't know how you're creating everything else, I came up with the following. Note that the shop() allows for overloading the parameters with the arguments object. The 'item' objects are encapsulated within an array which you can access as shown below.

```
  function shop() {
shopObj.shopType = arguments[0];
  if (arguments.length > 1)
// if you have more conditions, such as charisma, special quest item
  /*    switch (arguments.length) {
    case 1:
      ...etc...
    break;
    default:
  */

}

var shopObj = [
    {
        shopType: "Healer",
        shopAction : function() { engine.player.money -= itemCost; engine.player.revive(true); },
        itemCost : 100,
        itemName : "Heal"
    },
    {
        shopType : "Armory",
        shopAction : function() { engine.player.money -= itemCost; engine.player.inventory += itemName;},
        itemCost : 50,
        itemName : 'Dirk'
    }
]

for (i =0 ; i < shopObj.length; i++)
for (property in shopObj[i])
    alert( 'shop ' + i + " 's property is " + property +  " and it's value is " + shopObj[i][property])

```

Hope this helps Vinny
> 1 votes

---
Tags: javascript
---


title: Encode world matrix as 2 float4s?

text:
# Question
Title: Encode world matrix as 2 float4s?
On one of the slides of their presentation "Batch, Batch, Batch!" guys from NVidia suggest encoding animation matrices for pallet skinning into two float4s as:

> • axis/angle
>
> • translate/uniform scale

I wonder how can that be done (including decoding) and why do they say that this leads to:

> Video memory overhead: model replication

# Answer
> 2 votes
> Encode world matrix as 2 float4s

2 float4 means 2 vectors, encoding these in two vectors is easy and is actually common.

This can easily be done:

* axis/angle -\> axis ( x,y,z 3 floats ), angle ( 1 float ).
* translate/uniform scale -\> ( x,y,z 3 floats ), uniform scale ( 1 float ).

Now decoding this is as easy constructing a 4x4 matrix from scaling, rotation and translation.

Now my interpretation of

> Video memory overhead: model replication

If it caused video memory overhead, you can optimize it by using model replication, in other words use the same bone transforms for different models (instancing). Instead of submitting new transform for each new skeleton.

# Answer
> 2 votes
As concept3d said, a pair of float4s means 8 components total (so half the size of a 16-component matrix), and you can just fit a rotation, translation, and uniform scale value into 8 components. (Although I would use a quaternion rather than axis-angle - that way no trig functions need to be used in the vertex shader to apply the rotation.)

As for the "Video memory overhead: model replication" comment, this is my best guess:

The context of the talk is trying to reduce the number of batches (draw calls) by combining multiple models together in a batch. You would ordinarily have to create a new batch every time you changed the world matrix, so the speaker envisions doing this with bones instead ("matrix palette" is an old hardware feature for making bone matrices available to the vertex shader). Basically you'd attach each model to a different bone and set each bone to the transform needed for that object.

However, this raises a problem where the object has to know which bone it should be attached to. This would be done by adding a new vertex component for the bone index. But this means you need a vertex buffer with multiple copies of the model, each with the bone index set to a different value in all its vertices. Therefore you are paying a lot of video memory overhead by replicating the model several times.

Nowadays we would do all of this with instancing, which solves that problem; but I don't think hardware instancing existed in 2003 or 2004 when this talk was given.

---
Tags: matrix, skinning, palette
---


# Question
Title: Calculating step length with dividing a number that returns digits after the decimal point
How can I get rounded numbers from calculations that returns digits after the decimal point? And all the numbers together will be the number that is divided from.

**Explanation:**

I am currently working on an JavaScript tilebased-game with sprite animations.

Some walk/run sprites are less or more.

Let's say I have 3 walk sprites for walking down.

1: Look down

2: walkanimation sprite

3: walkanimation sprite

The distance between each tile, let's say, is 16 pixels.

16 pixels divided by 3 sprites is 5.33333.

So if the player walks down, each animationsprite wil move 5.3333 pixels down. That will end up that the player is at 15.999 pixels when the walk animation is done.

That will become not nice if the player walks down many times.

So I want to dynamically get the steps length which end up at the number that is divided from.

In this example:

16 / 3

Will return:

1/3: 6

1/3: 5

1/3: 5

Total: 16 pixels walked

# Answer
> 1 votes
It sounds like what you're after is a version of the *Bresenham Algorithm* for line-drawing: in effect, you're drawing a line that goes, e.g., 3 'sprixels' (that is, sprite-pixels) in one direction, and 16 pixels in the other, and you need to know what spans of pixels correspond to which sprixel.

If you don't care about evenly distributing 'long' and 'short' steps, then there's a very straightforward naive algorithm:

```
int spriteSteps[spriteCount];
int minSteps = totalSteps/spriteCount;
int extraSteps = totalSteps % spriteCount;
for ( i = 0; i < spriteCount; i++ ) {
    if ( i >= extraSteps )
        spriteSteps[i] = minSteps;
    else
        spriteSteps[i] = minSteps+1;
}

```

This will fill the spriteSteps\[\] array with the appropriate number of pixels for each sprite.

If you *do* want to distribute long and short steps as evenly as possible across your full set of sprites, then you should look at the Bresenham algorithm mentioned above, specifically *span* versions of it; it's not substantially more complicated than what I just gave. In effect, an accumulated error is used to determine when to flip from one span to the next.

Note that both of these algorithms have one major advantage: they both use nothing but integer arithmetic. In general, there's no reason to go to float for an algorithm like this, and many excellent reasons to avoid it.

# Answer
> 0 votes
I'm not sure what you're asking, but what's wrong with division & the modulus? The modulus ("%" in javascript) returns the remainder of a division.

```
 16 % 3 = 1
 26 % 3 = 2
 33 % 3 = 0.

```

# Answer
> 0 votes
Sorry for adding the code as another answer, but I'm more used to vbulletin boards & their markup codes than this markdown system.

jsFiddle Code, as well as below

```
<script>
numofSprites = 8;
stepLength = [];
function doit(pixelLength){
var remainder = pixelLength % numofSprites;
for (i = 0; i < 3; i++){
    var extraStep = 0;
    if (remainder != 0) {
                extraStep =  1
            remainder--;
            }

    stepLength[i] = (Math.floor(pixelLength/numofSprites) +  extraStep);
    alert(' pixelLength = ' + pixelLength + ' step'+i+ ' =' + stepLength[i])
     }
  }
doit(15)

</script>

```

---
Tags: javascript, animation, tilemap
---


# Question
Title: How can I place images on the terrain in SC2 maps?
I have seen this video where there are logos of the clans rendered on the ground in StarCraft 2.

How can I add images of my own in a custom map?

# Answer
> 1 votes
According to that video, it's a feature of that specific overlay client, not a feature of Starcraft II, so it cannot be done.

---
Tags: modding, starcraft-2
---


title: Multiple concurrent Tweens

text:
# Question
Title: Multiple concurrent Tweens
I'd like to be able to direct a game object to move to a new target position over a certain amount of time. There are lots of different easing functions available, but for now let's say I'm just planning to use a standard quadratic ease-in ease-out function and also a quadratic ease-out function.

For example

```
Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
};

```

Now suppose while it is still in the process of moving to that target and I want to give it a new target. Rather than have it instantly change directions with a zero starting velocity, I'd like a smooth transition.

How is this done mathematically and programmatically?

I want to avoid keeping a dynamic array of tween commands for every parameter of each game object. (I want to tween all sorts of parameters besides position.) that could get really heavy and bloated. But that's the only thing that comes to mind that might work... Keeping an array of active tweens and averaging all of them.

Maybe some easing functions lend themselves better toward being interrupted? Or is there a way to recalculate the four inputs to the ease function when a new target is set, such that the same function can continue to be used once per frame without a jarring speed/direction change, and ending at the second target instead?

# Answer
> 1 votes
A standard "tween" algorithm usually works by simplifying a more general hermite spline function, to eliminate the necessity of manually providing initial and terminating velocity values.

But if you wish to be able to switch from one tween to another, you can no longer do that, and you'll need to use a full, non-simplified spline calculation.

Here's some pseudocode which will work for floats or mathematical vectors (substitute 'type' for whatever value type you're interpolating between):

```
type SplineValueAtTime( float t, type start, type startVelocity, type end, type endVelocity )
{
    float tSquared = t * t;
    float tCubed = tSquared * t;

    float a = 2.f * tCubed - 3.f * tSquared + 1.f;  // 2t^3 - 3t^2 + 1
    float b = tCubed - 2.f * tSquared + t;          // t^3 - 2t^2 + t
    float c = -2.f * tCubed + 3.f * tSquared;       // -2t^3 + 3t^2
    float d = tCubed - tSquared;                    // t^3 - t^2

    type result = (a * start) +
                  (b * startVelocity) +
                  (c * end) +
                  (d * endVelocity);

    return result;
}

```

The code above calculates a spline with the specified start, end, and velocities at each end. 't' is assumed to vary in the range \[0..1\]. (If 'startVelocity' and 'endVelocity' are both zero, then this math simplifies down into the standard hermite interpolator, `start + ((3*t*t-2*t*t*t) * end-start)`)

Now all you need is to be able to figure out the object's current velocity at the time when it changes its interpolation target, so that you can create a new interpolation spline starting from its current position and velocity, and ending up at the desired new location.

Here's code to calculate the velocity at any particular point of the spline: (This is just the derivative of the above calculation)

```
type SplineVelocityAtTime( float t, type start, type startVelocity, type end, type endVelocity )
{
    float tSquared = t * t;

    float a = 6.f * tSquared - 6.f * t;             // 6t^2 - 6t
    float b = 3.f * tSquared - 4.f * t + 1;         // 3t^2 - 4t + 1
    float c = -6.f * tSquared + 6.f * t;            // -6t^2 + 6t
    float d = 3.f * tSquared - 2.f * t;             // 3t^2 - 2t

    type result = (a * start) +
                  (b * startVelocity) +
                  (c * end) +
                  (d * endVelocity);

    return result;
}

```

So with the information from these two functions, you can seamlessly change from one interpolation to another. Whenever you interrupt a transition with a new one, begin the new one using the item's current position and velocity (as determined by the two functions above), set 'end' to the new desired endpoint, and set endVelocity to `0` if you want an "ease-out", or to whatever other velocity you want the item to have at the end of the motion. (`end-start` is often a reasonable choice, if you don't want ease-out on the motion)

Hope that helps!

---
Tags: objects, tweening, easing
---


# Question
Title: OnClick events - using Scaleform UI with Cryengine 3.5.4
I've created a UI in Flash, set up an xml file for it and designed a flowgraph to ensure it displays when I launch. **However**, clicking on the buttons doesn't appear to do anything, despite me writing a click event in AS, linking to it in the xml, and connecting the function to a level change in the flowgraph.

XML:

```
<UIElements name="zlogicGUI2">

<UIElement name="GuiV2" render_lockless="1">

<Gfx file="GuiV2.gfx" layer="0">
<Constraints>
<Align mode="dynamic" valign="center" halign="center" scale="0" max="0" />
</Constraints>
</Gfx>

<events>
<event name="OnClick" ExternalInterface="ButtonClickPressed" desc="" />
</events>

</UIElement>

</UIElements>

```

ActionScript 3 (created in Flash CC)

```
button_1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);

function fl_MouseClickHandler(event:MouseEvent):void
{
    ExternalInterface("ButtonClickPressed");
}

```

# Answer
Cryengine only supports as2 so youll need to use flash cs6.
> 0 votes

---
Tags: flash, actionscript-3, gui, xml, cryengine
---


title: Masking away part of image with mesh

text:
# Question
Title: Masking away part of image with mesh
I need to remove a section of an image using a 2D mesh. Since the image is destructible (artillery game style), it would be helpful to shrink the image in memory afterward. The portion in the blue section should be kept, the portion in red is within the mesh and should be removed. Note that the image is rotated as well.

# Answer
> 1 votes
Here's my possibly naive way of doing it:

I. Create a render target the same size as the image that will be partially erased (should be transparent). I'll call this render target **brush**.

II. Render the polygon, offset relative to the image's origin and size, *in white* to **brush**, here shown with checkers and border to indicate transparent section.

III. Either set the render target to the image to be erased **or** create a render target that is a copy of the original. I'll call this target **canvas**.

IV. Draw the image to **canvas** using non-premultiplied alpha blending.

V. I came up with the following blend state in XNA to use for the next step

```
_blendErase = new BlendState
{
    ColorBlendFunction = BlendFunction.Add,
    AlphaBlendFunction = BlendFunction.ReverseSubtract,

    ColorSourceBlend = Blend.One,
    AlphaSourceBlend = Blend.One,

    ColorDestinationBlend = Blend.InverseSourceAlpha,
    AlphaDestinationBlend = Blend.InverseSourceAlpha,
};

```

VI. Use that blend mode to draw **brush** to **canvas**, again shown with checkers to indicate the transparent area.

Optional: Scan from the polygon's center toward the far edge of the image to find the new edge of the pixels, then trace the edge (eg using marching squares) to adjust its bounding box.

**Note:** This doesn't seem work with pre-multiplied alpha images, although I'm probably doing that wrong.

---
Tags: xna, masking
---


# Question
Title: Problem using glm::lookAt and glm::perspective
I'm trying to change the code from the 22th tutorial at http://ogldev.atspace.co.uk/, using the GLM library, but the result seems wrong. The problem is shown in the below picture: While it should be:

This program displays a model onto the screen. The model is loaded using a library and I ensure that all of its vertices, normals, and texuture coordinates are loaded correctly. The problem seems to be at creating the Projection - model - view matrix. I searched for the use of GLM and use the below code to calcualate that matrix:

```
    glm::vec3 Pos(3.0f, 7.0f, -10.0f);
    glm::vec3 Target(0.0f, -0.2f, 1.0f);
    glm::vec3 Up(0.0, 1.0f, 0.0f);

    glm::mat4 viewMat = glm::lookAt(Pos, Target, Up);
    glm::mat4 perMat = glm::perspective(60.0f, (float)WINDOW_WIDTH/WINDOW_HEIGHT, 1.0f, 100.0f);

    glm::mat4 modelMat = glm::scale(glm::mat4(1.0f),glm::vec3(0.1f, 0.1f, 0.1f));
    modelMat = glm::rotate(modelMat, m_scale, glm::vec3(0.0f, 1.0f, 0.0f));
    modelMat = glm::translate(modelMat, glm::vec3(0.0f, 0.0f, 10.0f));

    //FINAL MATRIX
    glm::mat4 PVMMat = perMat * viewMat * modelMat;

```

After that, I supplied the matrix to the shader like this:

```
glUniformMatrix4fv(m_WVPLocation, 1, GL_TRUE, &PVMMat[0][0]);

```

Finally, in the shader, I calculate the gl\_Position as below:

```
//vertex shader
void main()
{
    gl_Position = gWVP * vec4(Position, 1.0);
    TexCoord0   = TexCoord;
    Normal0     = (gWorld * vec4(Normal, 0.0)).xyz;
    WorldPos0   = (gWorld * vec4(Position, 1.0)).xyz;
}";
//Fragment shader
void main()
{
    FragColor = texture2D(gSampler, TexCoord0.xy);
}";

```

I tried my best for a few days and I can't see any error in the way I use glm::lookAt and gml::perspective. This is exactly as in the manual on the GLM website. Could you suggest some reason for the problems I'm seeing, or some way for me to further investigate the error? Thanks so much. I hope to see your answer.

# Answer
> 2 votes
The problem is solved.

I changed

```
glUniformMatrix4fv(m_WVPLocation, 1, GL_TRUE, &PVMMat[0][0]);

```

to:

```
glUniformMatrix4fv(m_WVPLocation, 1, GL_FALSE, &PVMMat[0][0]);

```

and:

```
glFrontFace(GL_CW);

```

to:

```
glFrontFace(GL_CCW);

```

---
Tags: opengl, c++, fragment-shader, glm
---


title: How to set speed of circular motion

text:
# Question
Title: How to set speed of circular motion
**Edit 2 - clarification**

Just to clarify, the issue I have at the moment is how I specify a time (in seconds) for a complete revolution to occur. My delta is fixed and is 1/ticks per second (1/60). As you can see with my linear sprite movement, I have a 'time' variable which is where I specify (in seconds) how long the sprite should take to travel the length (or height) of the screen. I'm looking at how I do this for circular movement.

**Edit 1 - Results from suggestions**

See at end of question.

**Background**

When moving my sprites along a straight path, I'm using delta so I can get the same rate of relative motion on all devices like so:

```
spriteGridX = 240/480;  //I start out with a virtual 'Grid' so I can scale position to all resolutions etc so 240/480 would place the sprite at the center of the screen (X)

spriteScreenX = spriteGridX * width;  //Scale to physical screen where width is the width of the current devices screen (viewport)

spriteXTime = 8f; //8 being the amount of time in seconds that this sprite will take to traverse the entire width of the screen

spriteXVel = 1/spriteXTime; //Velocity that will be used to move the sprite along the virtual grid position

```

So, when I need to move the sprite, I simply do the following:

```
spriteXGrid+= (spriteXVel * Delta) //+= for right -=for left. I'm using a fixed delta time
spriteScreenX = spriteGridX * width; //And again, convert to usable screen position for current device
drawsprite(spriteScreenX, SpriteScreenY); //Draw the sprite (drawSprite is just a method I've written to draw openGL quads and it takes the screen X and Y as coordinates - spriteScreenY not shown here but essentially same as X with height instead of width.

```

Now, I need to have a sprite move along a circular path. So far, I have a test up and running which directly acts on the 'screen' coordinates of the sprite directly like so:

*Java Code*

```
int rad = 25;
float angle = 50;

spriteScreenX-=Math.round(rad*Math.cos(angle));
spriteScreenY+=Math.round(rad*Math.sin(angle));
angle+=.1;

```

**The Problem**

Now, the above *does* work, but the sprite completes it's circular path way too quickly (it's doing approximately 1 revolution per second).

So my question is:

* Am I doing this correctly and if so..........
* How do I slow this down? I won't particularly need to keep changing the speed, I just want to be able to set it initially.

Would really appreciate some pointers.

**Edit 1**

When I put the following the code above I get the following result:

If I put the following:

```
spriteScreenX-=Math.round(rad*Math.cos(angle*Math.PI/180*delta));
spriteScreenY+=Math.round(rad*Math.sin(angle*Math.PI/180*delta));
angle+=.1;

Or:

spriteScreenX-=Math.round(rad*Math.cos(angle*delta));
spriteScreenY+=Math.round(rad*Math.sin(angle*delta));
angle+=.1;

```

Something like this happens:

# Answer
> 1 votes
The solution I used for anyone who comes across this problem was this:

**Initial Setup**

```
int rad = 200;       //Radius in px
float angle = 0;     //Angle (this needs to be represented in radians, not degrees)
float centreX;       //X Coordinate of the centre of rotation
float centreY;       //Y Coordinate of the centre of rotation
float time;          //Number of seconds a full revolution should take
int ticksPerSecond   //Number of game updates per second
float spriteX;       //X Position of sprite
float spriteY;       //Y Position of sprite

```

**To rotate the sprite**

```
//Update the angle

angle+= 2 * Math.PI / (ticksPerSecond * time);

//Update the coordinates

spriteX = (centreX  + (rad*Math.cos(angle)));
spriteY = (centreY  + (rad*Math.sin(angle)));

```

I've tested this at various screen resolutions and time settings and the sprite rotates according to the *time* variable (i.e. specify 10 seconds and it will take 10 seconds for 1 complete revolution to occur).

Changes in the time setting will not alter the radius of the orbit's path and the opposite is also true.

If you want to set the initial angle of the object around the orbit-path, then simply specify in radians

```
angle = (angle in degrees)/180 * Math.PI

```

# Answer
> 0 votes
`Math`'s trig functions use radian so multiply the angle by `Math.PI/180` before passing as parameter

you can apply a delta to the angle to reduce the speed

if you want to rotate along a specific point `(px, py)` then you can do the following

```
double tmpx = spriteXGrid - px;
double tmpy = spriteYGrid - py;

double resultx = tmpx*Math.cos(angle*Math.PI/180*delta)-tmpy*Math.sin(angle*Math.PI/180*delta) + px;
double resulty = tmpy*Math.cos(angle*Math.PI/180*delta)+tmpx*Math.sin(angle*Math.PI/180*delta) + px;

```

# Answer
> 0 votes
You are using `+=` to modify the position directly from the angle. Effectively, you aren't updating the position along an arc, you are updating the direction of movement. So when you slow it down, all you get is a direction that changes more slowly, which means a bigger circle.

To use a radial velocity, you would need the center of rotation. But that seems like a cumbersome extra bit of data to store. It would be simpler to store and update speed separately from direction. Then you could always update the position according to a single frame's instantaneous velocity, rather than calculating some offset based on a radius, then calculating the angle traverse, turning that back into a position, etc.

For example:

```
// class members

//    speeds
double spriteVel;
double radian_speed;  // can be zero while not turning

//    positions
double positionx;
double positiony;
double radians_angle;

//update

double speed = (spriteVel * Delta);

radians_angle += (radians_speed * Delta);

double directionx = Math.cos(radians_angle);  // from -1 to 1
double directiony = Math.sin(radians_angle);  // from -1 to 1

positionx += speed * directionx;
positiony += speed * directiony;

```

Now if you increase the angular speed, the object will turn in a smaller radius. It would still be possible to calculate the radius of the turn. The math will be very simple, if you use radians. :)

# Answer
> 0 votes
Forget approx. You can get the thing to move in 1 circle **exactly** 1 time per sec.

A sinusoid `sin( 2*M_PI*freq*t )` makes `freq` cycles per second.

Your framerate is kinda irrelevant to the sinuosoid. If you are using a framerate of 60 fps, just *fix your timestep* to `timeStep=1./60`. Now if `t` represents "clocktime", the sinusoid will progress at `freq` cycles per second. The sinusoid doesn't care that your t is discrete.

Also, don't accumulate your sin offset. What you want to do is specify a *centroid* position, and the sin/cos values are the **offsets** that get applied on each frame.

The position of a sprite moving in a circle of radius `r` with centroid `c` should be computed as

```
px = cx + r*cos( 2*M_PI*freq*t ) ; // t is accumulated "real" time, 1/60 first frame, 2/60 2nd frame..
py = cy + r*sin( 2*M_PI*freq*t ) ;

```

---
Tags: java, animation, sprites, rotation
---


# Question
Title: Will function-local objects affect my performance over time?
This is a very simple question.

Let's say my render loop runs at 60Hz, in each call to render(), I draw all my game's buildings, characters and scenery to make the current frame ready. Each of these entities are drawn using its own instance of a RectangleShape, which is a class able to render a texture to the screen. (I am using OpenGL but it shouldn't be relevant)

RectangleShape is a class that once allocated, generates geometry for the "sprite" to be drawn, has some properties to configure and then renders itself using OpenGL.

The problem is, for each entity, I am allocating the RectangleShape object, configuring and rendering it inside render(). So, in practice, there are dozens if not hundreds of blocks like this inside render():

```
// pseudocode
RectangleShape entitySprite;
entitySprite.setSize();
entitySprite.setTexture();
entitySprite.render();

```

I am aware I have a performance decrease by not using a pre allocated RectangleShape, already configured, which I only call render() on. I know that is the optimal path to go, but my question is:

Will so many allocations/deallocations of RectangleShape (hundreds, 60 times a second) fragment memory over time, decreasing the performance of the whole program? Or can I be safe that despite the performance hit by on-demand allocation is constant and will not degenerate as time passes?

I am not using any kind of custom allocator for anything. Also, please have in mind that the RectangleShape constructor internally resizes a std::vector, which I think implies a heap allocation.

Thanks

# Answer
> 2 votes
Assuming that you're in C++ (which is what your code looks like), creating local instances of `RectangleShape` inside a function will not cause memory fragmentation. Those variables are being created on the stack, and so their memory will cleanly go away when the stack frame is cleaned up when the function returns.

Do note, though, that if the `RectangleShape` itself allocates memory on the heap using `new` or `malloc()` (or certain other `malloc()`-like calls), then those allocations could conceivably lead to memory fragmentation, depending on what other heap allocations are occurring and how long-lived those other allocations might be.

---
Tags: performance, optimization, memory
---


# Question
Title: Rotate final image with projection matrix
I'm trying to use space in my shadow (depth) maps in a more efficient way. If I could freely rotate the final image I get with projection matrix I could save a lot of pixels, but I don't know if it is possible to do so. Is it?

# Answer
You can rotate the shadow map view by inserting a Z-rotation matrix between the view and projection matrices. This is like rolling the shadow map camera, which causes the resulting shadow map image to rotate in 2D.
> 1 votes

---
Tags: rotation, matrix, projection
---


# Question
Title: Ship Controls modeling Real life Physics
I am working on a 2D ship that will fly around in space (for now, no friction or gravity). The controls are similar to the game Asteroids. My problem is that I am having trouble connecting some variables to real life applications.

For example, if I'm defining the ships velocity, which in real physics is V=distance traveled (or change in position)/time. Should velocity be a Vector2 or just a float (or int). It's how far an object moves so I would think it to be just a single integer or number but then again, your moving on an X and Y axis so shouldn't there be two velocities? One for the X and another for the Y? The velocity being a vector2 actually works really well but when I'm doing other formulas, which are floats or ints, that require velocity I run into issues because I don't have a single number then.

Another issue i'm having trouble grasping is the direction. My code for the direction is:

```
shipVariables.shipDirection = new Vector2((float)Math.Sin(shipVariables.shipRotation), -(float)Math.Cos(shipVariables.shipRotation));

```

Which works but it will immediately turns the ship if you rotate the object while moving "forward". My most successful approach to this method was doing this:

```
shipVariables.shipDirection += new Vector2((float)Math.Sin(shipVariables.shipRotation), -(float)Math.Cos(shipVariables.shipRotation));

```

The effect I like is that instead of just turning, it essentially has to overcome the previous direction to move to the next. The part I don't like is that it gains speed way to much and it's supposed to just be a direction, not a direction and magnitude.

If I have the velocity and I can get the direction, I will be able to calculate everything else with other formulas that I know (momentum, acceleration, etc...).

Any tips to lead me in the right directions would be great, thanks.

# Answer
Physics for simple points in 2D is basically the same as doing 1D physics twice - once for each dimension (X and Y). So you can use the same formulas you would use on `float`s on `Vector2`s and it generally "just works".

But if you add rotation, you must calculate a 1D angular "dimension" as well. (It's more of a "degree of freedom".)

So start with your variables:

```
float angle;
// You could have a "float angularVelocity" here if you wanted
Vector2 position;
Vector2 velocity;

```

And then update something like this:

```
if(leftKey)
    angle -= rotateAmount;
if(rightKey)
    angle += rotateAmount;

// Note: A proper cartesian coordinate system with "Y+ = up" would be (cos, sin).
//       But I'll just use what you have:
Vector2 direction = new Vector2((float)Math.Sin(angle), -(float)Math.Cos(angle));

float thrust = thrustKey ? 1f : 0f;

velocity += direction * thrust * time;
position += velocity * time;

```

Finally: Generally don't use `int` for physics. It is for integer (whole) values, which makes it difficult to get the desired results. A `Vector2` is made up of two `float`s.
> 2 votes

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


# Question
Title: How can I move an object diagonally on Windows Phone?
I want to pull a sprite from point A(vector2) to point B(vector2) in my Windows Phone XNA game. GestureType.HorizontalDrag moves it horizontally and GestureType.VerticalDrag moves it vertically, how can I move the sprite diagonally?

The player should be able to pull the sprite in every direction if he touches the sprite with his finger. The sprite can't be moved if the player's finger isn't on the sprite.

How can I do that? How can I move an object diagonally on Windows Phone?

# Answer
> 0 votes
There is `GestureType.FreeDrag` that may do what you want (MSDN).

Otherwise, it may be worth implementing your own touch behaviour using `TouchPanel.GetState()`

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


# Question
Title: Farseer Circle Body Problems, Please help!
I have created a circle body class, but in game my player body just passes through it. the circle will not move, only rotate.

however when i create the circle body just straight up, raw in the game1 load content method, without using a personalised class, it works. so im thinking i have done something wrong but i cant for the life of me spot it.

here are the two different implementations, the first is the class and its instance in the game1 class, THAT doesn't want to move the circle around or collide properly, the second is the classless implementation directly in the load content method of the game1 class.

```
    class CircleBody
{
    Texture2D Texture;
    Vector2 Origin;
    Vector2 Position;
    public Body Circle;

    public CircleBody(Texture2D texture, Vector2 position, World world)
    {
        this.Texture = texture;
        this.Origin = new Vector2(this.Texture.Width / 2f, this.Texture.Height / 2f);
        this.Position = new Vector2(ConvertUnits.ToSimUnits(position.X), ConvertUnits.ToSimUnits(position.Y));
        Circle = BodyFactory.CreateCircle(world, ConvertUnits.ToSimUnits(56 / 2), 1f, this.Position);
        Circle.BodyType = BodyType.Dynamic;
        Circle.Restitution = 0.3f;
        Circle.Friction = 0.5f;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(this.Texture, ConvertUnits.ToDisplayUnits(this.Position), null, Color.White, this.Circle.Rotation,
            this.Origin, 1f, SpriteEffects.None, 0f);
    }

```

here is the above class instanced and implemented in the game1 class:

Variables:

```
        CircleBody CircleBody;
        Texture2D CircleTexture;

```

Load Content Method:

```
    CircleTexture = Content.Load<Texture2D>("Player");
    CircleBody = new CircleBody(CircleTexture, new Vector2(400, 300), world);

```

Drawing:

```
    CircleBody.Draw(spriteBatch);

```

it just doesn't work :(,

HOWEVER it works perfectly when I create it in a different way, as in not through my own class, but raw within the game1 class. here is the code.

Variables:

```
     Texture2D playerTex;
     Vector2 playerOrigin;
     Body player;

```

LoadContent Method

```
    playerTex = Content.Load<Texture2D>("Player"); //
    playerOrigin = new Vector2(playerTex.Width / 2f, playerTex.Height / 2f);
    /* Circle */
     Convert screen center from pixels to meters
    Vector2 playerPosition = ConvertUnits.ToSimUnits(screenCenter);
     Create the player fixture
    player = BodyFactory.CreateCircle(world, ConvertUnits.ToSimUnits(56 / 2), 1f, playerPosition);
    player.BodyType = BodyType.Dynamic;
    player.Restitution = 0.3f;
    player.Friction = 0.5f;

```

Drawing:

```
   spriteBatch.Draw(playerTex, ConvertUnits.ToDisplayUnits(player.Position), null, Color.White, player.Rotation,
                playerOrigin, 1f, SpriteEffects.None, 0f);

```

The first method through the class is obviously the cleaner and perfect way i want to implement the creation of a circle based body sprite combination, but i dont understand why the sprite is not moving, or collidable or seemingly alive in the simulation.

and i really dont see why it works raw in game1 class.

i really hope you can help!!! im sooooo stuck

# Answer
Change this line:

```
Vector2 Position;

```

To this:

```
Vector2 Position { get { return Circle.Position; } set { Circle.Position = value; } }

```

And then pass your `new Vector2` directly into `BodyFactory.CreateCircle`.

---

What is happening here is that `Vector2` is a "value type" and not a "reference type".

When you pass a value type (as you do to the `BodyFactory.CreateCircle`), it takes a *copy* of that value type, leaving the original alone. So *your* `Position` variable is not being modified when the Farseer body moves.

(Whereas, if `Vector2` were a reference type, then it is the *reference* that gets copied - not the object instance the reference refers to. So then you might expect the `Body` class to keep your object instance updated - although the exact behaviour would be defined by `Body`.)

In this case, the simplest work-around would be to change `Position` from being a variable, to a property that simply access the correct `Vector2` out of the `Body` class.

An alternative might be just access `Circle.Position` directly.
> 0 votes

---
Tags: c#, 2d, farseer-physics-engine
---


title: java Game: Rendering issue!

text:
# Question
Title: java Game: Rendering issue!
Hi I am making a java game in were you can build land. At the moment you can build but not destroy. So I want to be able to destroy. I have an array of the tiles. I think I might need to do something like remove the tile that the mouse is hovering on form he arraylist so how can I do this? I don't think you need my code to explain to me because I only want to know how to remove the Tile that the mouse is hovering over. Please help me.

EDIT\**** MY array is a arraylist kind of arraylist and I have an arraylist for each block.

# Answer
If you have an linear array which stores tiles, you can easily find the current tile by taking the mouse position and dividing it by the dimensions of your world.

So bascily like this :
int2 iTilePos = MousePos.XY / int2( TerrainWidth, TerrainHeight );
int index = iTilePos.Y * TerrainWidth + iTilePos.x;

What happens here is that you are dividing the mouse position down to the size of the world, and from there you just map it linearly. Since the amount of Y steps equals one full Width. And finaly adding the last steps in the current width. ( which in this case would be the iTilePos.X)
> 0 votes

---
Tags: java
---


# Question
Title: How do game developers make their game available for most of the resolutions?
I'm developing a game with Java using Slick2D and I want to make a game that could target all the recommended resolutions, as you can see in almost every game you could have an option of changing the resolution. I would like to know how game developers make their game assets once and use different screen resolutions and it still looks good.

My only guess is that when you're in game (playing-moving, jumping) the viewport of the camera is set to some size at the same aspect ratio of the player's monitor.

How do game developers do this? Not just in-game, even when just browsing the menu.

# Answer
> 1 votes
On my android project, I achieved resolution independence by defining a VIRTUAL\_SIZE(The "safe" area) and SCREEN\_SIZE (The actual size of the screen). I further define SCALE to be the lesser of VIRTUAL\_SIZE.X/SCREEN\_SIZE.X and VIRTUAL\_SIZE.Y/SCREEN)SIZE.Y. This ensures that I can scale up while still fitting the screen. Then any objects such as buttons or images are scaled up with SCALE and are drawn in a centered safe area defined by VIRTUAL\_SIZE, while any "filler" such as background or particles are drawn into an unsafe area defined by SCREEN\_SIZE.

Using this technique your playable area might not fill the screen, however you are given complete control of the game mechanics (game won't run differently on different devices) without limiting the visuals.

Of course you can always use different techniques. As an example, for some games you may need to enforce a variable height while always ensuring the width is the maximum.

---
Tags: slick, assets, resolution
---


# Question
Title: How can I use touch input for 3rd-person controls?
I have a 3rd-person controller in my Unity scene, which I can only control with the *WASD* buttons. But since I plan to make a smartphone game, I wonder how I can change these controls t *swipe up/down/right/left* and (if possible) keep *WASD* for debugging.

# Answer
Do this in character controller script's `Update()`

First of all you have to detect the user input via touch(begin/moved/ended) methods and then you have to calculate the gesture it ended up in like swipe-left. You can assign a bool to it like `SwipeL = true;`

Now you have to add a condition in the methods where character movement is mapped with `Input.GetKey("A")` etc and append your `bool` with OR condition

e.g.

```
if(Input.GetKey("A") || SwipeL)
{
//code for moving left
}

```

You need to do this for all key mappings.
> 3 votes

---
Tags: c#, unity, touch, control
---


title: Implementing frame-independent friction

text:
# Question
Title: Implementing frame-independent friction
So I'm not looking for anything realistic like a physics engine, just want to say that first. I'm working on a simple top-down game and I'm trying to get friction working with deltaTime.

This was my old code:

```
friction = Math.pow(0.99f, deltaTime * maxFPS);

```

This worked well and I applied the friction each frame. However, I need to refactor this code since I do not know what the possible **maxFPS** will be (it could be 30, 60, 120 - it depends on the device limitations).

So here's my new code:

```
friction = Math.pow(0.6f, deltaTime);

```

This eliminates the need to know the **maxFPS** and gives me (roughly) the same output value to apply each frame.

---

My issue is this: I do not just set the friction to a static value, it changes depending on other factors.

So with my old code, for example, the value I would raise to a power to get friction would range anywhere from **0.6f to 1.0f**.

With the new code, I have to use different values since the power is different, so the new range would be **0.0000000000001f to 1.0f**.

This just doesn't seem (and feel, when playing the game) right. The range is way too big and from 0.2 - 1.0f the results are all nearly the same value (0.98+, very "slippery" friction) - it doesn't seem like a linear gradient (if that makes sense) the way **0.6f - 1.0f** with my old method was.

Just wondering what the common method is to implement frame-independent friction, if I'm doing it right and if there is anything I can do to get the same "feel" I was getting before.

# Answer
I don't know what your simple physics looks like, but if you're making a simple top-down shooter you probably have position, velocity, and acceleration, right?

In these terms, you would do this every frame if `deltaTime` returns number of milliseconds in between frames:

```
pos += vel * deltaTime / 1000;
vel += accel * deltaTime / 1000;

```

That gets your objects moving in a reasonable manner.

I've found that implementing friction in these systems as a drag on velocity in the absence of acceleration "feels" right. It's easy to reason about, easy to calculate by hand, and makes a sensible relation right back to velocity:

```
if (accel == 0) {
  if (vel - friction > 0) {
    vel -= friction;
  } else {
    vel = 0;
  }
}

```

You'd of course have to check for negative and positive and for x-axis and y-axis. I left all that out to simplify the sample code.

One thing to be careful of with this method: make sure to cap `deltaTime` to something reasonable, like 50 milliseconds, otherwise your velocities will go insane under a big time step.
> 1 votes

# Answer
I would highly recommend that you decouple your physics (even if very simple) time-step from your frame rate. It is much easier to think about and more predictable. Also, if you are doing simple Euler integration, then it is best to keep the physics time step very small to keep the inevitable errors as small as possible. If your physics calculations are inexpensive, then a small enough time-step (several per frame) will avoid the need to interpolate the values from adjacent time-steps too.
> 3 votes

# Answer
To add to D. Hayes answer (I can not comment yet I'm afraid). The physically correct friction for objects sliding on a surface is simply a constant, say 'fr', working opposite to the direction of movement (source: http://faculty.wwu.edu/~vawter/physicsnet/topics/Dynamics/Forces/FrictionalForce.html). So

```
if(vel > 0)
 vel -= fr*dt
else if(vel <0)
 vel += fr*dt
vel += accel*dt;

```

for objects moving trough a medium (water, air) the friction is linear in the velocity, or quadratic at high speeds.(source: http://hyperphysics.phy-astr.gsu.edu/hbase/airfri.html) so

```
vel -= fr*v*dt;
vel += accel*dt;

```

or

```
vel -= fr*v*v*sign(v)*dt;
vel += accel*dt

```
> 2 votes

# Answer
If you're simulating your physics in fixed steps (say your game runs at variable fps but physics is at 15fps), then you could add a callback or function that is called before each physics 'tick'. This way any forces are applied evenly regardless of what your logic is running at.
> 1 votes

---
Tags: java, android, mathematics
---


title: unity sphere falls through the plane

text:
# Question
Title: unity sphere falls through the plane
I have a elongated rigidbody sphere with Mesh Collider. It falls through the plane. (I made a rigidbody cube and does not fall through.)

I have problem with Mesh Collider repeately.. The collision of the object is not detected.

If I replace the mesh collider with box collider, it collides again.

I would like to collide a mesh collider with another mesh collider.

# Answer
A Mesh Collider can not collide with another Mesh Collider unless Convex is checked on the Collider in question.

This is described in the Unity3D documentation: http://docs.unity3d.com/Documentation/Components/class-MeshCollider.html
> 2 votes

---
Tags: unity
---


title: Multiplying matrices in HLSL

text:
# Question
Title: Multiplying matrices in HLSL
I have code that calculates a position like this in HLSL:

```
output.ShadowPos = input.VertexPos;
output.ShadowPos = mul(output.ShadowPos, gWorld);
output.ShadowPos = mul(output.ShadowPos, lightArray.lightView);
output.ShadowPos = mul(output.ShadowPos, lightArray.lightProject);
output.ShadowPos = mul(output.ShadowPos, T);

```

This works fine, but I would like to multiply the matrix together first

```
matrix m = gWorld * lightArray.lightView * lightArray.lightProject * T;
output.ShadowPos = input.VertexPos;
output.ShadowPos = mul(output.ShadowPos, m);

```

Yet this doesn't work, why?

# Answer
> 3 votes
Do your matrix multiplications like vector\*matrix, like this:

```
matrix m = mul(gWorld,mul(lightArray.lightView,mul(lightArray.lightProject,T)));

```

---
Tags: mathematics, directx, matrix, hlsl
---


# Question
Title: Rigidbody2D hanging when moving across set of colliders (tiles)
I've got a player object that has a Rigidbody2D and CircleCollider2d attached to it, and I'm trying to make it move across a large field of tiles, each exactly next to one another and each identical in size. For some reason, the player object occasionally gets stuck on what looks to be points between tiles. Any ideas on why this is happening, or what I can do to fix it? Thanks!

# Answer
> 1 votes
Yeah, what is happening is numerical error is getting your Collider stuck. It's especially bad with AABBs. Basically you're catching a tiny edge between the two blocks you are walking on. This is usually not a problem with games that represent cubes in a grid, as the cubes are implicit geometry in this way. However in Unity you're using a full rigid body engine, and this problem arises.

Things you might try would be to lower friction, not set the position of your player but only update it's velocity (let the physics inside Unity integrate your velocity), don't apply gravity to the player if it is in a "grounded" state. You can try to "merge" many cubes that lay within the same plane and form one giant rectangle, this way the player does not walk over tiny gaps at all.

There's a lot of specific solutions if you have access to the physics engine source (that I am not mentioning), but someone else might know some Unity specifics. I myself have not used Unity.

---
Tags: unity
---


title: Point vs Convex Hull

text:
# Question
Title: Point vs Convex Hull
I'm trying to implement a simple collision response to a point intersecting a convex hull.

So far I can detect if the point is inside the hull.

But now I want a collision response that translates and rotates the hull away from the point so it no longer intersects.

I'd like the simplest algorithm possible, I don't want to implement a physics engine or rigid bodies.

Can someone point me in the right direction?

# Answer
I would ignore the answer about GJK.

Since you can detect if the point is in your polygon, all you need to do find which face is the axis of minimum penetration. This tells you what direction to press your two objects apart. This direction is called the collision normal.

In order to know this you will be using the results of your plane tests. When you do collision testing against your polygon you can compute the distance of the point to each face plane. Keep track of the greatest signed value. If the greatest signed distance is negative then you know the point lies within the polygon. This greatest signed distance (which is still negative) comes from the plane which is the axis of minimum penetration. This distance is your penetration depth.

Once you have this axis you use the face normal of this plane as the direction of which to press these two objects apart. Exactly how you press them apart can be extremely simple or very complicated. Since you asked for something simple I'll recommend modifying position directly.

Take the position of your polygon and move it along the collision normal a distance equivalent to the penetration depth.

This resolution is called linear projection and it is very simple. You can also rotate your object accordingly, if you so wish. This gets more complicated. You can also apply an impulse to the velocity and integrate your velocity to move the position -this can result in a more stable and physically accurate resolve. If you want to know more about this try searching for "Impulse Resolution", I wrote some articles about this topic.
> 3 votes

# Answer
You can use the GJK distance algorithm as well as a simple iterative contact resolver.

Basically, given a position and rotation of the body expressed as functions of time *t*, you want to solve for a value of *t* that reduces the distance from the point to the edge of the convex hull to exactly zero, and integrate the body using that time value. It's possible to do this analytically, but for a game it's more efficient (and much easier) to do it numerically.

With the numerical method, you just incrementally change *t* until you get a distance value that lies within an acceptable threshold. The simplest way to do this is to switch the direction you change *t* and also reduce the magnitude of the delta whenever the point switches from interior or exterior, or vice versa. A more complex algorithm (that will also converge in fewer steps) will increment based on the arc length between the point and the body (this is what Bullet does in its CCD solver).

Note that this only makes sense when you know the linear and angular velocities of the body, or reduce the movement to either translation or rotation, not both. Otherwise, the problem is vastly underdetermined and will have a huge number of complex solutions.
> 0 votes

---
Tags: collision-detection, collision-resolution, convex-hull
---


title: Why doesn't my XNA model render at all?

text:
# Question
Title: Why doesn't my XNA model render at all?
I am trying to draw a 3D Model in XNA 4.0, but it doesn't show up. I think I made it correctly, but maybe not. My code follows:

Here is the `LoadContent` and `Draw` method of my `Main` class. `Spaceship` is a class representing the model I want to draw.

```
    private Spaceship _spaceship;
    private Matrix _view, _projection;

    protected override void LoadContent()
    {
        _spaceship = new Spaceship(Game, Game.Content.Load<Model>("spaceship"), Vector3.Zero);

        _view = Matrix.CreateLookAt(_spaceship.CamPos, new Vector3(0, 0, 0), Vector3.UnitY);
        _projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45),
            Game.Window.ClientBounds.Width / Game.Window.ClientBounds.Height, 1f, 100f);
    }

    public override void Update(GameTime gameTime)
    {
        _view = Matrix.CreateLookAt(_spaceship.CamPos, new Vector3(0, 0, 0), Vector3.UnitY);
    }

    public override void Draw(GameTime gameTime)
    {
        _spaceship.Draw(_view, _projection);
        base.Draw(gameTime);
    }

```

Here is the `Spaceship` class.

```
    private Vector3 _camPos;
    protected Matrix _world;

    public Vector3 CamPos
    {
        get { return _camPos; }
    }

    public Spaceship(Game game, Model spaceship, Vector3 position)
    {
        _game = game;
        _model = model;
        _position = position;

        Initialize();
    }

    private void Initialize()
    {
        _camPos = new Vector3();

        _camPos.X = Position.X;
        _camPos.Y = Position.Y;
        _camPos.Z = Position.Z + 10;
    }

    public override void Update(GameTime gt)
    {
        _world = Matrix.Identity * Matrix.CreateTranslation(_position);

        _camPos.X = Position.X;
        _camPos.Y = Position.Y;
        _camPos.Z = Position.Z + 10;
    }

    public virtual void Draw(Matrix view, Matrix projection)
    {
        ModelDrawer.DrawModel(_model, _world, view, projection);
    }

```

Finally, this is my `ModelDrawer` class's `DrawModel` method:

```
    public static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
    {
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.World = world;
                effect.View = view;
                effect.Projection = projection;
            }

            mesh.Draw();
        }
    }

```

This is what the model looks like in Sketchup before I export to `.fbx`.

# Answer
Seems that I simply missed a line of code in the main class update method.

```
 _spaceship.Update(gameTime);

```
> 1 votes

---
Tags: c#, 3d, xna-4.0, models
---


# Question
Title: Which parts to draw in an infinite world?
I have an infinite world (from Perlin Noise).

The world is generated in sectors that are that are big cubes (each with a random colour, in the image above; my sectors are 10x10x10).

I'm currently putting the sectors in a hash-table tagged by their top-left-front corner coordinate. I can loop through all the sectors I've already generated and see if they intersect the frustum.

But how can I compute instead the sectors that I haven't generated but are visible and need generating on-demand?

Even if I have an octree or some other spatial index, I need to compute the sectors that are visible inside the frustum rather than those I've already generated.

# Answer
just generate and keep all blocks within a X radius of the player in the hash table, and then frustum filter for drawing, same way minecraft does it

it's cheaper to keep more sectors in memory and then filter than keep just enough and generate
> 1 votes

---
Tags: procedural-generation, culling, frustum
---


# Question
Title: Unity3d NullReferenceException: Object reference not set to an instance of an object
I'm making a script to climb ladders in my game. These are the variables used in the function.

```
private Vector3 climbDirection = Vector3.zero;
private Ladder currentLadder = null;
private bool latchedToLadder = false;

```

And here is the function

```
void LatchLadder (GameObject latchedLadder, Collider collisionWaypoint){
    currentLadder = latchedLadder.GetComponent<Ladder>();
    latchedToLadder = true;
    climbDirection = currentLadder.ClimbDirection();
    gameObject.SendMessage("OnLadder",null,SendMessageOptions.RequireReceiver);

}

```

Everytime I collide with the ladder in playmode i get

```
NullReferenceException: Object reference not set to an instance of an object
UseLadder.LatchLadder (UnityEngine.GameObject latchedLadder, UnityEngine.Collider collisionWaypoint)
UseLadder.OnTriggerEnter (UnityEngine.Collider other)

```

at

```
climbDirection = currentLadder.ClimbDirection();

```

Anyone can see what's the cause ?

# Answer
The object you're colliding with does not have the Ladder component. If you try to get a component from an object that doesn't have it, `GetComponent` will return null. You should check to make the sure component isn't `null` before doing anything with it, but you should probably make sure the object you're trying to latch on to is a ladder in the first place. You can do that by checking to see if it has the ladder component.

Before you call `LatchLadder`, perform a check similar to:

```
//inside your collide function
if(collidedGameObject.GetComponent<Ladder>() != null) {
    //it has the ladder component, it's a ladder
    LatchLadder(collidedGameObject, collisionWaypoint);
} else {
    //we've collided with something that isn't a ladder, do something else.

}

```
> 3 votes

# Answer
Most likely latchedLadder has no Ladder component, in which case `latchedLadder.GetComponent<Ladder>();` returns null;
> 1 votes

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


# Question
Title: What size textures do I need for a 2D grid based game if my tiles are larger than textures I have?
I'm building a grid-based game for iPad, and for usability purposes I've selected my game grid to be built of 75x75 squares. However, so far I've seen that the majority of (free)texture catalogs I can find are either 16x16 or 32x32.

Currently I have the graphics engine stretch the 32x32 texture onto a 75x75 tile, which does not look very sharp.

How can I make my game look good - **do I need to create textures whose size is equal to my game tile?** Should I try to stitch multiple textures together (like 4 texture squares per game square)?

# Answer
Yes, you will have to create images at the desired resolution.

Whether you should stitch textures together can not be answered. It depends on what textures you use and what the result looks like, nothing else. Alternatively reduce the grid size.
> 3 votes

---
Tags: 2d, textures, sprites, tiles, grid
---


# Question
Title: How can I apply an effect to a sound to simulate hearing it underwater?
I'm using XNA 4.0 and trying to reproduce an "underwater effect" for every sound played.

How can I apply an effect to a sound, and what effect should I use to make it sound like as if the player is underwater while hearing it?

# Answer
DynamicSoundEfectInstance might be a good start.

Load the sound into a buffer from a file, then apply a custom low-pass filter to it.

See this question for more detailed information on adjusting audio in XNA.
> 2 votes

---
Tags: xna, sound, sound-effects
---


# Question
Title: How to use Bullet physics with Entity Component Systems?
I have an Entity Component system and I want to have a `Physics` Component that would add the given object to the physics simulation.

My problem arises because the Bullet API requires me to add each object before doing the simulation.

How should I proceed to create a System(System in entity component terms) that wraps the Bullet Physics API to do simulation while the `Physics` components are getting added and removed?

Edit:

This is how my Entity component system looks like.

```
class Entity
{
    std::unordered_map< size_t, void* > components;
public:
    // setters getters for components based on key
}
class EntitySystem
{
    std::unordered_map< size_t, Entity* > entities; // maps entity GUID to entity*
public:
    // calls function on all entities
    void Process( void* userdata, void (function*)(void*, Entity*) );

    // Entity creation, setting, getting, component index management, etc...
}

```

# Answer
> 4 votes
There's no need to shove a pre-made physics engine into a particular model. All good physics engines are going to be using some form of data oriented design; you can't have a fast physics engine without cache optimization. This means that any benefits from attempting an Entity Component System, or any other data oriented approach will be redundant.

What you can do is write small wrappers that are stored as components in your engine. I'm not familiar with exactly how Bullet works, but I do know most engines have colliders and rigid bodies separated. What is usually done is a collider is represented with a component type, and a rigid body is represented with a different component type. This allows the separate wrappers to support dynamic transferring of the colliders to attach or remove themselves from rigid bodies.

You can apply any programming paradigm to your own wrappers. I honestly think that any wrapper will be perfectly fine. If Bullet does not support run-time modification of the physics objects, then you're out of luck.

---
Tags: architecture, entity-system, bullet-physics
---


# Question
Title: Implementing collision response, current implementation does too many checks
I don't know how I should handle my collision response when collision between two entities leads to second collision with third entity.

*Blue arrow is velocity of the rightmost entity and numbers below are single collision response.*

**Single Collision**

At the beginning leftmost and middle entities are not colliding with each others, but after rightmost entity collides with middle one, the velocity middle entity gains now causes it to collide with leftmost one

**How end result should be**

*Or if the leftmost entity was a wall -\> 0, 0, -v*

**Current implementation:** check collisions until all are handled

Velocities before collision handling

* 0, 0, \<-10
* Collisions: 2&3

*If entity velocity is changed due the collision do new check*

After 1. collision check:

* 0, \<-5, \<-5
* Collisions: 1&2

After 2. collision check:

* \<-2.5, \<-2.5, \<-5
* Collisions: 2&3

After 3. collision check:

* \<-2.5, \<-3.75, \<-3.75
* Collisions: 1&2

After 4. collision check:

* \<-3.125, \<-3.125, \<-3.75
* Collisions: 2&3

After nth collision check:

* \<-3.33, \<-3.33, \<-3.33
* No collisions
* Continue

**Question:** As we clearly see, it takes way too many collision checks to fix even simple collisions this way. How should I improve or redo this?

**Sample code written with sfml:**

I have 3 types of entities in my test case:

* wall
* pushable
* passable

*Entity, velocity and boundingRect:*

*Collision response:*

* wall \<-\> pushable: can't move inside wall, push pushable entity away
* pushable \<-\> pushable: both are repelled from each others so they won't collide
* wall\<-\>wall: skip collision checks between walls and all checks with passable terrain

Controls in sample code

* Arrow keys: move green entity
* Left mouse button: spawn pushable entities
* Right mouse button: spawn wall entities
* Middle mouse button: spawn moving pushable entities

.

```
#include <SFML/Graphics.hpp>
#include <iostream>

const sf::Vector2f entitySize(16.f, 16.f);

bool isMovingUp = false;
bool isMovingDown = false;
bool isMovingRight = false;
bool isMovingLeft = false;

enum Category
{
    wall,
    pushable,
    passable,
};

class Entity
{
    public:
        Entity(sf::Vector2f position, sf::Color color, Category type) : position(position), type(type)
        {
            shape.setSize(entitySize);
            shape.setFillColor(sf::Color::Transparent);
            shape.setOutlineColor(color);
            shape.setOutlineThickness(1.f);
        }

        sf::Vector2f position;
        sf::Vector2f velocity;
        sf::Vector2f adjustedVelocity;
        sf::Vector2f defaultVelocity;
        sf::RectangleShape shape;
        Category type;
};

void DrawEntity(sf::RenderWindow& window, Entity& entity)
{
    entity.shape.setPosition(entity.position - entity.shape.getSize() / 2.f);
    window.draw(entity.shape);
}

sf::FloatRect GetBoundingRect(const Entity& entity)
{
    return sf::FloatRect(entity.position+entity.velocity - entitySize / 2.f, entitySize);
}

void HandleCollision(std::vector<Entity>& entities)
{
    bool allCollisionsChecked = false;

    while(!allCollisionsChecked)
    {
        allCollisionsChecked = true;

        // Pair all possible combinations, but only once per pair
        for (auto first = entities.begin(); first != entities.end(); ++first)
        {
            for (auto second = std::next(first); second != entities.end(); ++second)
            {
                if (first->type == Category::passable || second->type == Category::passable || first->type == Category::wall && second->type == Category::wall)
                    continue;

                sf::FloatRect intersection;
                if (GetBoundingRect(*first).intersects(GetBoundingRect(*second), intersection))
                {
                    if (second->position == first->position)
                        second->position.x += entitySize.x;

                    sf::Vector2f direction = second->position - first->position;
                    sf::Vector2f offset;

                    // X collision
                    if (abs(direction.x) > abs(direction.y))
                        offset.x = ((direction.x<0)?-1:1)*intersection.width;

                    // Y collision
                    if (abs(direction.x) < abs(direction.y))
                        offset.y = ((direction.y<0)?-1:1)*intersection.height;

                    if(first->type == Category::pushable && second->type == Category::pushable)
                    {
                        first->velocity -= offset / 2.f;
                        second->velocity += offset / 2.f;
                        allCollisionsChecked = false;
                    }
                    else if(first->type == Category::pushable)
                    {
                        first->velocity -= offset;
                        allCollisionsChecked = false;
                    }
                    else if(second->type == Category::pushable)
                    {
                        second->velocity += offset;
                        allCollisionsChecked = false;
                    }
                }
            }
        }
    }
}

void handlePlayerInput(sf::Keyboard::Key key, bool isPressed)
{
    switch(key)
    {
    case sf::Keyboard::Up:
        isMovingUp = isPressed;
        break;
    case sf::Keyboard::Down:
        isMovingDown = isPressed;
        break;
    case sf::Keyboard::Left:
        isMovingLeft = isPressed;
        break;
    case sf::Keyboard::Right:
        isMovingRight = isPressed;
        break;
    }
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(1280, 720), "SFML Application");
    window.setVerticalSyncEnabled(true);

    std::vector<Entity> entities;

    Entity player(sf::Vector2f(1280/2, 720/2), sf::Color::Green, Category::pushable);
    entities.push_back(player);

    size_t cols = 1280/int(entitySize.x);
    size_t rows = 720/int(entitySize.y);

    for (size_t i=0; i < cols*rows; ++i)
        if (i%cols == rows/5 && i/cols > rows/6 && i/cols < rows*5/6 || i%cols >= rows/5 && i%cols <= rows*4/5 && (i/cols == rows/6 || i/cols == rows*5/6))
            entities.push_back(Entity(sf::Vector2f(entitySize.x*(i%cols)+entitySize.x/2, entitySize.y*(i/cols)+entitySize.y/2), sf::Color::Yellow, Category::wall));
        //else
            //entities.push_back(Entity(sf::Vector2f(entitySize.x*(i%cols)+entitySize.x/2, entitySize.y*(i/cols)+entitySize.y/2), sf::Color::Transparent, Category::passable));

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::MouseButtonPressed)
            {
                sf::Vector2i pixel(event.mouseButton.x, event.mouseButton.y);
                sf::Vector2f coord = window.mapPixelToCoords(pixel);

                if (event.mouseButton.button == sf::Mouse::Left)
                {
                    Entity pushable(coord, sf::Color::Blue, Category::pushable);
                    entities.push_back(pushable);
                }
                else if (event.mouseButton.button == sf::Mouse::Right)
                {
                    Entity wall(coord, sf::Color::Yellow, Category::wall);
                    entities.push_back(wall);
                }
                else if (event.mouseButton.button == sf::Mouse::Middle)
                {
                    Entity mover(coord, sf::Color::Magenta, Category::pushable);
                    mover.defaultVelocity.x = -1.f;
                    entities.push_back(mover);
                }
            }

            switch (event.type)
            {
                case sf::Event::KeyPressed:
                    handlePlayerInput(event.key.code, true);
                    break;

                case sf::Event::KeyReleased:
                    handlePlayerInput(event.key.code, false);
                    break;

                case sf::Event::Closed:
                    window.close();
                    break;
            }
        }

        if (isMovingUp)
            entities[0].velocity.y -= 5.f;
        if (isMovingDown)
            entities[0].velocity.y += 5.f;
        if (isMovingLeft)
            entities[0].velocity.x -= 5.f;
        if (isMovingRight)
            entities[0].velocity.x += 5.f;

        if (entities[0].velocity.x != 0.f && entities[0].velocity.y != 0.f)
        {
            entities[0].velocity.x /= std::sqrt(2.f);
            entities[0].velocity.y /= std::sqrt(2.f);
        }

        HandleCollision(entities);

        // Apply and reset velocities
        for (Entity& e : entities)
        {
            e.position += e.velocity;
            e.velocity = e.defaultVelocity;
        }

        // Draw
        window.clear();
        for (Entity& e : entities)
            DrawEntity(window, e);
        window.display();
    }
}

```

**Sample results**

Magenta entities are moving to the left with constant speed and yellow entities are wall.

*without checking collisions due the other collisions*

**Desired outcome:**

*Same scenario when checking collisions until all are resolved*

How could I achieve this?

# Answer
Usually collision that happen due to the result of resolution will be resolved on the next simulation loop. Most games (basically all of them afaik) do this.

The only time I would think about solving collisions that are caused by resolution, within the same frame, is if interpenetration is something that is fundamentally banned by the physics simulation. This is the case when using continuous collision detection (which nobody should be doing, except in special cases like raycasting).

In short, don't worry about it. If you have physics problems it is not because you aren't solving collisions caused by resolution.
> 4 votes

---
Tags: c++, collision-resolution, sfml
---


title: Angluar movement

text:
# Question
Title: Angluar movement
I'm making a little game where you are a spaceship and you fly around in 2d using the A and D key to rotate and the W key to accelerate. Now my problem is if i turn my ship it doesn't go into the right direction, it is very random actually...

```
    public void update(GameContainer gc, int i) throws SlickException {
    Input input = gc.getInput();
    if(input.isKeyDown(Input.KEY_D)) {
        rotationDegree += 20;
        System.out.println(rotationDegree);
    }

    if(input.isKeyDown(Input.KEY_A)) {
        rotationDegree -= 20;
        System.out.println(rotationDegree);
    }

/// if(rotationDegree > 360) rotationDegree = 0;
//  if(rotationDegree < 0) rotationDegree = 360;
     rotationRadian = Math.toRadians(rotationDegree);
    if(input.isKeyDown(Input.KEY_W)) {
         position.x = (float) (position.x + 3*Math.sin(rotationRadian/25));
         position.y = (float) (position.y + 3*Math.cos(rotationRadian/25));
         System.out.println(position.x);
         System.out.println(position.y);
    }
}

```

# Answer
Here try this:

```
Vec2 Vec2::Rotated( real radians ) const
{
  real c = std::cos( radians );
  real s = std::sin( radians );

  real xp = x * c - y * s;
  real yp = x * s + y * c;

  return Vec2( xp, yp );
}

```

This shows how to rotate a vector given a scalar. You can use this knowledge to rotate a vector into the direction of the ship. You can then scale this vector (if it is normalized) by a distance (like speed) and move the ship along this vector.
> 1 votes

# Answer
I believe that you need to use cosine for x and sine for y , so it would be

```
position.x = (float) (position.x + 3*Math.cos(rotationRadian/25));
position.y = (float) (position.y + 3*Math.sin(rotationRadian/25));

```

But I don't know why you would divide by 25.
> 0 votes

---
Tags: 2d, rotation, movement
---