# Question
Title: In a graph-based material system, how can I support a variety of input and output types?
**I'm trying to wrap my head around how material systems like this, this are implemented.** These powerful and user-friendly, graph-like systems seem to be *relatively common* as a method of allowing programmers and non-programmers alike to quickly create shaders. However, from my relatively limited experience with graphics programming, I'm not entirely sure how they work.

---

**Background:**

So, when I've programmed *simple* OpenGL rendering systems before, I typically create a Material class that loads, compiles, and links shaders from static GLSL files that I've manually created. I also usually create this class as a simple wrapper for accessing GLSL uniform variables. As a simple example, imagine that I have a basic vertex shader and fragment shader, with an extra uniform Texture2D for passing a texture. My Material class would simply load and compile those two shaders into a material, and from that point on it would expose a simple interface for reading/writing the Texture2D uniform of that shader.

To make this system a little bit more flexible, I usually write it in a way that allows me to attempt to pass uniforms of any name/type *\[i.e.: SetUniform\_Vec4( "AmbientColor", colorVec4 ); which would set the AmbientColor uniform to a particular 4d vector called "colorVec4" if that uniform exists in the material.\]*.

```
class Material
{
    private:
       int shaderID;
       string vertShaderPath;
       string fragSahderPath;

       void loadShaderFiles(); //load shaders from files at internal paths.
       void buildMaterial(); //link, compile, buffer with OpenGL, etc.

    public:
        void SetGenericUniform( string uniformName, int param );
        void SetGenericUniform( string uniformName, float param );
        void SetGenericUniform( string uniformName, vec4 param );
        //overrides for various types, etc...

        int GetUniform( string uniformName );
        float GetUniform( string uniformName );
        vec4 GetUniform( string uniformName );
        //etc...

        //ctor, dtor, etc., omitted for clarity..
}

```

This *works* but it feels like a bad system due to the fact that the client of the Material class has to access uniforms on faith alone - the *user has to be somewhat aware of the uniforms that are in each material object because they're forced to pass them by their GLSL name.* It's not a huge deal when it's just 1-2 people working with the system, but I can't imagine this system would scale very well at all, and before I make my next attempt at programming an OpenGL rendering system, I want to level up a bit.

---

**Question:**

That's where I am so far, so I've been trying to study how other rendering engines handle their material systems.

This node-based approach is great and it seems to be an extremely common system for creating user friendly material systems in modern engines and tools. From what I can tell they're based on a graph data structure where each node represents some shader aspect of your material and each path represents some kind of relationship between them.

From what I can tell, implementing that kind of system would be as simple a MaterialNode class with a variety of subclasses (TextureNode, FloatNode, LerpNode, etc.). Where each MaterialNode subclass would have MaterialConnections.

```
class MaterialConnection
{
    MatNode_Out * fromNode;
    MatNode_In * toNode;
}

class LerpNode : MaterialNode
{
    MatNode_In x;
    MatNode_In y;
    MatNode_In alpha;

    MatNode_Out result;
}

```

That's the *very basic* idea, but I'm a little bit uncertain about how a few aspects of this system would work:

**1.)** If you look at the various 'Material Expressions' (nodes) that Unreal Engine 4 uses, you'll see that they each have input and output connections of a variety of types. Some nodes output floats, some output vector2, some output vector4, etc. **How can I improve the nodes and connections above so that they can support a variety of input and output types?** Would subclassing MatNode\_Out with MatNode\_Out\_Float and MatNode\_Out\_Vec4 (and so on) be a wise choice?

**2.) Finally, how does this kind of system relate to GLSL shaders?** Looking again at UE4 (and similarly for the other systems linked above), the user is required to eventually plug a some material node into a large node with various parameters that represent shader parameters (base color, metalness, gloss, emissiveness, etc.). My original assumption was that UE4 had some kind of hard coded 'master shader' with a variety of uniforms, and everything that the user does in their 'material' is simply passed to the 'master shader' when they plug their nodes into the 'master node'.

However, the *UE4 documentation* states:

> "Each node contains a snippet of HLSL code, designated to perform a specific task. This means that as you construct a Material, you are creating HLSL code through visual scripting."

If that's true, **does this system generate a real shader script? How exactly does this work?**

# Answer
> 12 votes
I'll try to answer to the best of my knowledge, with little knowledge about the specific case of UE4, but rather on the general technique.

Graph based materials are as much programming as writing the code yourself. It just doesn't feel like it for people with no background on code, making it seemingly easier. So, when a designer links a "Add" node, he is basically writing add(value1,value2) and linking the output to something else. This is what they mean that each node will generate HLSL code, either its a function call or just straightforward instructions.

In the end, using the material graph is like programming raw shaders with a library of predefined functions that do some common useful things, and that's also what UE4 does. It has a library of shader code that a shader compiler will take and inject into the final shader source when applicable.

In the case of UE4, if they claim its converted to HLSL, I assume they use a converter tool which is able to convert HLSL byte code into GLSL byte code, so its usable on GL platforms. But other libraries just have multiple shader compilers, which will read the graph and directly generate the needed shading language sources.

The material graph is also a nice way to abstract from platform specifics and focus on what matters from a art direction point of view. Since its not bound to a language and much higher level, its easier to optimize for the target platform and dynamically inject other code like light handling into the shader.

1) Now to answer your questions more directly, you should have a data-driven approach to designing such a system. Find a flat format that can be defined in very plain structures, and even defined in a text file. In essence, each graph should be an array of nodes, with a type, a set of inputs and outputs, and each of these fields should have a local link\_id to make sure graph connections are unambiguous. Also, each of these fields could have additional configuration to what the field supports (what range of data types are supported, for example).

With this approach, you could easily define a node's field to be (float|double) and let it infer the type from the connections, or force a type into it, with no class hierarchies or overengineering. It's up to you to design this graph data structure as rigid or flexible as you want. All you need is that it has enough information so that the code generator will not have ambiguity and therefore potentially handling wrong what you want to do. The important is that at the basic data structure level, you keep it flexible and focused on solving the task of defining a material alone.

When I say, "define a material" I am very specifically referring to defining a mesh surface, beyond what the geometry itself provides. This includes using additional vertex attributes to configure the aspect of the surface, add displacement to it with a heightmap, disturb the normals with per-pixel normals, changing physically based parameters, to change the BRDF's and so on. You don't want to describe anything else like HDR, tonemapping, skinning animation, light handling or a lot other things done in shaders.

2) It is then up to the renderer's shader generator to traverse this data structure and by reading its information assemble a set of variables and link them together using premade functions and injecting the code that calculates lighting and other effects. Just remember that shaders vary not only from different graphics API's, but also between different renderers (a deferred rendering vs tile based vs forward renderer all require different shaders to work), and with a material system such as this, you can abstract from the nasty low level layer, and focus only on describing the surface.´

For UE4, they came up with a list of things for that final output node you mention, which they think describes 99% of the surfaces in old and modern games. They developed this set of parameters over decades and proved it with the insane amount of games the Unreal engine has produced so far. Therefore you will be just fine if you do things the same way as unreal.

To wrap it up, I suggest a .material file just to handle each graph. During development, it would contain perhaps a text based format to debug and then be packaged or compiled to binary for release. Each .material would be composed by N nodes and N connections, a lot like a SQL database. Each node would have N fields, with a name and some flags for types accepted, if its input or ouput, if the types are inferred, etc. The runtime data structure to hold the loaded material would be just as flat and simple, so the editor can easily adapt it and save back to file.

And then leave the actual heavy lifting for the final shader generation, which is really the hardest part to do. The beautiful part is that your material stays agnostic to the rendering platform, in theory it would work with any rendering technique and API as long as you represent the material in its appropriate shading language.

Let me know if you need additional details or any fixing in my answer, I lost the overview over all the text.

---
Tags: shaders, rendering, materials
---


title: Cocos2d-x 3.0 animation frame by frame

text:
# Question
Title: Cocos2d-x 3.0 animation frame by frame
As I know animations are actions. Now I need to play animation frame by frame. Say I have an animation from `N` frames. each frame should be played after `t` delay. Now I want to play animation frame by frame, each frame advance the animation's state. How I can do this?

And what about playing actions frame by frame advancing the state in general.

I ask because I use ECS, and I deal with frames.

P.S. I want to do something like this:

```
Action * a = MoveTo(initialPoint, finalPoint, durationOfAnimation);

a->play(0.001 seconds);
a->play(0.003 seconds);
a->play(0.02 seconds);
a->play(0.67 seconds);
a->play(0.06 seconds);

```

And see the animation.

# Answer
I think you can call a-\>update(0.001) - see the doc of Action's update : http://www.cocos2d-x.org/reference/native-cpp/V3.0/db/d61/classcocos2d\_1\_1\_action.html#ac8cae2d59252ed4c924a6c0ec86527db

So instead running the action automatically call the update yourself.
> 0 votes

# Answer
You can play an animation and :

```
animation->setDelayPerUnit(T);

```
> 0 votes

---
Tags: animation, cocos2d-x
---


# Question
Title: How to get display resolution (screen size)?
How to get display resolution in XNA/Monogame ? I tried these on my monitor (1600x900):

The below give me 800,600

```
//1.
GraphicsDevice.DisplayMode.Width
GraphicsDevice.DisplayMode.Height

//2.
GraphicsDeviceManager graphics = new GraphicsDeviceManager(this);
graphics.GraphicsDevice.DisplayMode.Width
graphics.GraphicsDevice.DisplayMode.Height

//3.
GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width
GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height

//4.
foreach (DisplayMode dm in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
{
    Console.WriteLine(dm.Width);
    Console.WriteLine(dm.Height);
}

```

# Answer
This one worked:

```
using System.Drawing
using System.Windows.Forms
_ScreenWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
_ScreenHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;

```

A much better solution is:

```
ScreenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
ScreenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;

```
> 2 votes

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


# Question
Title: How to order points on a 3D grid such that we can connect them in a line loop correctly
I want to recreate an effect as close as possible to X-Com: Enemy Unkown's movement range feedback:

<sub>(source: gameinformer.com)</sub>

The blue line delimits the tiles which the soldier can reach using a single action. We also are using a 3D grid approach in our game. We are not developing this with a pre-built engine, so I'd like some sort of algorithm which I am not aware of, not some engine's feature (unless it is well documented). We've discussed using things like quickhull, but quickhull generates a convex contour, while this contour can be concave or convex.

Any thoughts or ideas? Thank you for all your input

Edit: Yes, we already have the centers of the tiles which are the "edge" or outermost tiles of the walkable area. What we're not sure about is the following:

From the green center, given just the points, we could draw both the red and yellow contours. How do we know which one is the correct one? What data would we need?

Final edit: One of the programmers on my team figured out something which is good enough for our purposes. It is not exactly the same as the output of whatever X-Com is using.

We take the whole tiles given to us by the Dijkstra pathfinding algorithm on the set of tiles and start at one which we can guarantee is an edge. We define a forward direction and a perpendicular vector to that direction. The direction vector is the one used to walk between tiles and the perpendicular vector is used to check whether there is an adjacent tile in that direction to which the forwrad direction must be rotated to. If none of those point to a valid tile, we rotate away from the perpendicular vector. An accompanying image will follow so that we can explain it better for anyone else who wants to accomplish a similar effect.

# Answer
One of the programmers on my team figured out something which is good enough for our purposes. It is not exactly the same as the output of whatever X-Com is using.

We take the whole tiles given to us by the Dijkstra pathfinding algorithm on the set of tiles and start at one which we can guarantee is an edge. We define a forward direction and a perpendicular vector to that direction. The direction vector is the one used to walk between tiles and the perpendicular vector is used to check whether there is an adjacent tile in that direction to which the forward direction must be rotated to. If none of those point to a valid tile, we rotate away from the perpendicular vector.

Image with explanation:

This is the in-engine result:
> 0 votes

# Answer
* Create your points so they form a solid line on a 2D plane.
* Walk the line starting with a point that's on ground level, for each point:
    + If the ground is above or below the current position, add a new point, and shift the existing point and all remaining points up or down to meet the height of the ground. -Continue until all points have been touched.

You can think of this like projecting the line down from above the world.
> 1 votes

# Answer
First of all, I think the grid is pseudo-3d: 2D movement area, but create vertical lines when the height changes. Given that, check this answer, as the same principle applies.
> 1 votes

# Answer
Hmm... like the other answerers, I'm going to make some guesses about unclear information in the question.

My assumptions:

* Your map is essentially 2d, and projected downward onto the walkable surface
* Your map is represented as a set of polygonal areas
* Adjacent areas share 2 (or more) vertices

If that's true, one approach is to:

* Collect the edges of the accessible areas, including the one you're on (if you're allowed to stay there)
* Count duplicates (edges used by more than one area polygon)
* Throw away edges used more than once

The remaining edges form the 2d accessible outline. You could join them to make a closed loop if needed. Project downward to walkable areas. Draw.

Bonus feature -- works even if the accessible area is noncontiguous, for example if you're not allowed to stay where you are, or there are wormholes in the map.
> 0 votes

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


# Question
Title: Environment collision in a pseudo-3d 2d space
The game is a 2D brawler with depth movement in the vein of Golden Axe, Final Fight, Castle Crashers etc. Characters and environment are all 2d sprites as well. I've had no real issue setting up collision between characters to take the depth into account either.

However, it's just not a proper brawler without higher ground to jump to and pits to throw the enemy into, and that is where I run into a bit of an issue with how best to implement it.

I considered making the collision boxes for the level in the 3D space and having the sprites just translate the z movement of their game object into y movement of the visual component, but I don't particularly like that approach because it feels difficult to work with for doing the level design of matching 3D colliders to a drawn backdrop and placing objects in there.

Any suggestions for a design that is the 2D first, so to speak? Ideally being able to "paint" height levels and pits in the 2D design wise. If it matters, I'm working in unity with a primarily 2d space (though involving the third dimension here will be necessary), but I think the base design problem would be fairly engine/language agnostic.

# Answer
I think you might be able to achieve this in a 2D space by using multiple box colliders - or just just a range of x & y values, really. I spent a few hours in GIMP editing this up:

Depicted is an open manhole that the turtles can fall in. Just a singular box collider would work for pits, but I used the screen wide colliders for illustration.

For elevated platforms, you could do something like this:

If you the player was colliding with the lower platform, it would make the player eligible for standing on the upper platform (in some way of your choosing). In this picture, the upper platform is well above the typical walkable area of the stage, but using this technique, you could easily have platforms you could walk behind, around, and under, by using a combination of colliders - this way elevated platforms could overlap with the ground you could already walk on. I think it'd boil down to something like this:

```
public class ElevationChecker : MonoBehaviour {
public PlayerClass player;
public Collider upperPlatform;
....
// Where this trigger is the ground collider
public void OnTriggerExit(Collider playerFeet) {
    if (player.isJumping) {
        upperPlatform.enabled = true;
    }
}
....
// You could later disable the upper collider once the player walks off it
// so they could walk around, under, etc
}

```

There may be things you need to work out here yourself, but I think this general approach would allow you to keep a strictly 2D style and not bother with 3D.
> 2 votes

---
Tags: unity, collision-detection, game-design, level-design
---


title: View frustrum culling

text:
# Question
Title: View frustrum culling
I have a model structured like this:

```
 1. Root model

     1.1.Child model 1

     1.2 Child model 2

     1.3 Child model 3

     1.4 .....

```

The model in question is the "sponza" model used in many research articles, for example viewed here, in an otherwise unrelated video: https://www.youtube.com/watch?v=uhmH1PaY9Sw

I have implemented a view frustrum culling alghorithm that produces INSIDE, OUTSIDE or PARTIAL results for each model. The problem is I'm not sure how to apply it when building my renderqueue.

Here's my current alghorithm:

* If model AABB it OUTSIDE, skip it and all its children
* If model is INSIDE || (PARTIAL && no child models), render it
* If model is PARTIAL and has children, dont render it but repeat process for its children

Is this the correct approach? I don't notice any particular performance benefits, unless the view frustrum is completely outside the root model...

```
void Engine::CullModels(const std::vector<ModelPtr>& allModels, const Mat4& viewProjectionMatrix, const Mat4& parentTransform)
{
    // TODO: not very cache-friendly
    // this could be a CPU-hotspot for complex scenes
    FrustrumIntersection aabbIntersection(FRUSTRUM_INTERSECTION_INSIDE);
    for (const ModelPtr model : allModels)
    {
        if (!model)
            continue;

        Mat4 worldMatrix = parentTransform;
        if (model->mSceneNode)
            worldMatrix *= model->mSceneNode->GetNodeTransform();
        const Mat4 worldViewProjMatrix = viewProjectionMatrix * worldMatrix;

        aabbIntersection = IsAABBInFrustum(model->GetAABBCenter(), model->GetAABBExtent(), worldViewProjMatrix);
        if (aabbIntersection == FRUSTRUM_INTERSECTION_OUTSIDE)
            continue;

        if (aabbIntersection == FRUSTRUM_INTERSECTION_PARTIAL && model->mMesh != INVALID_MESH_ID)
        {
            const MaterialPtr material(model->mMaterial);
            if (material)
                mRenderQueue.emplace_back(Renderable(model->mMesh, worldViewProjMatrix, worldMatrix, model->mMaterialTilingFactor,
                                                    Vec4(material->mDiffuseColor, 1.0f), Vec4(material->mAmbientColor, 1.0f), Vec4(material->mSpecularColor, 1.0f), Vec4(material->mEmissiveColor, 1.0f),
                                                     material->mDiffuseTexture, material->mNormalTexture, material->mSpecularFactor));
            else
                mRenderQueue.emplace_back(Renderable(model->mMesh, worldViewProjMatrix, worldMatrix));
        }

        CullModels(model->mChildren, viewProjectionMatrix, worldMatrix);
    }
}

```

# Answer
To test culling, you probably want to render to another target without the culling to see if your culling strategy is working as intended.

Second, rather than putting the visible objects into a collection, instead have a flag on each objects on whether or not they are visible. When drawing, skip objects with the flag set to false.

Assuming your view frustum culling algorithm is correct, you need to know whether or not your model is hierarchical, that is, whether the parent AABB fully contains all the children AABBs. If so, then its something like this:

If Parent is visible, render the parent and all its children.

If Parent is not visible, dont render parent and any of its children.

If Parent is partial, render the parent and repeat for every child.
> 1 votes

---
Tags: rendering, scene-graph, frustum-culling
---


title: moving from Glut to SDL2

text:
# Question
Title: moving from Glut to SDL2
I'm using Glut with OpenGL for drawing. Glut is very simple and straightforward but I have to give up Glut and move on toward SDL2. I'm reading SDL for Game Development, good book. I need to speed up a bit, so I'm looking for a list of comparisons between Glut and SDL2. At least with common similarities between the two. For example, in Glut we need for drawing `Display()` to be passed to `glutDisplayFunc()`. My understanding so far for SDL2 is that `SDL_Renderer` is like `Display()` in Glut. Is this correct? Also, what do exactly `SDL_Surface` and `SDL_RenderPresent` mean?

# Answer
I made the same transition recently. I'm not sure if what I'm doing is "SDL Best Practices" but it does work. It doesn't use and SDL\_Renderer or SDL\_Surface...

Here's a segment of my code. Much of it is pasted from forgotten internet pages. I *think* I left in everything relevant, after snipping out some of my app-specific goop. I hope it helps. (And feedback from anyone who knows better is definitely welcome here!)

As for the actual question, a comparison of glut to sdl, for me it was just:

GLUT:

* install callbacks for events like draw, keyboard mouse
* 1 special window by default

SDL2:

* your own main event loop, and switch on event type yourself
* explicit window creation & control

Example code:

```
SDL_Window *mainwindow; /* Our window handle */
SDL_GLContext maincontext; /* Our opengl context handle */

if (SDL_Init(SDL_INIT_VIDEO) < 0) /* Initialize SDL's Video subsystem */
    sdldie("Unable to initialize SDL"); /* Or die on error */

SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

// next line as per: http://stackoverflow.com/questions/11961116/opengl-3-x-context-creation-using-sdl2-on-osx-macbook-air-2012
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

/* Turn on double buffering with a 24bit Z buffer.
 * You may need to change this to 16 or 32 for your system */
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 32);

/* Create our window centered */
mainwindow = SDL_CreateWindow("The Window Name", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                              1600, 800, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

maincontext = SDL_GL_CreateContext(mainwindow);

/* This makes our buffer swap syncronized with the monitor's vertical refresh */
SDL_GL_SetSwapInterval(1);

/* Clear our buffer with a red background */
glClearColor ( 1.0, 0.0, 0.0, 1.0 );
glClear ( GL_COLOR_BUFFER_BIT );

/* Swap our back buffer to the front */
SDL_GL_SwapWindow(mainwindow);

SDL_Delay(200);

while (!quit)
{
  draw(); // does glDrawXxx stuff here.
  SDL_GL_SwapWindow(mainwindow);

  while (SDL_PollEvent(&e)){
    switch(e.type)
    {
      case SDL_QUIT:
        quit = true;
        break;

        case SDL_KEYDOWN:
         /* et cetera */
          break;
    }
}

```
> 1 votes

---
Tags: glut, sdl2
---


# Question
Title: Equalling the rotation of an image with its object. Box2dweb
I have some hard time making the rotation of an image equal to the rotation object that the image belongs to. Simply put it, I don't know how to do it properly but i am not asking for a how-to guide but for some tips/hint and/or infos that i am not aware of...

I was able to align perfectly the image with the object, and so if the object moves in a linear fashion the image is at all times on top of the object and everything is smooth and perfect. But how is it possible to make the rotation of the image be the same as of the object it belongs to.

No-matter what i tried it is always somewhat off or the rotation of the image behaves weird when in the end the object stops rotating. I tried using using GetAngle(), GetAngularVelocity(), combinations of both, but never succeeded.

```
function Draw_and_Rotate(){
   for (b = world.GetBodyList() ; b; b = b.GetNext()){
      var angle = ((b.GetAngle()*180)/(Math.PI))/SCALE;
      var angle_vel = ((b.GetAngularVelocity()*180)/(Math.PI))/SCALE;
      var pos = b.GetPosition();
      console.log((angle));
      if (b.GetUserData() == "bo_img"){
         ctx.save();//save the ctx state prior changing it.This method pushes the current state onto the stack.
         ctx.translate(pos.x*SCALE , pos.y*SCALE );
         ctx.rotate(angle);
         ctx.drawImage(box_img, - (box_img.width / 2), - (box_img.height / 2));
         ctx.restore();//restoring ctx state.This method pops the TOP state on the stack, restoring the context to that state.
      }

   }
}

```

this is the part that deals only with one body and its image. If someone needs some more clarification please ask....

# Answer
> 0 votes
replace this line: var angle = ((b.GetAngle()\*180)/(Math.PI))/SCALE; with this: var angle = b.GetAngle();

the input parameter in ctx.rotate should be in radians, so there is no need to convert it in your code in any way. The output of b.GetAngle() is in radians.

---
Tags: javascript, box2d
---


# Question
Title: Draw my array at a position defined with Vector2
I'm developing a space invaders game in C# using XNA Game Studio. So I got some of the invader logic complete: An array holds the invaders and draws them on the screen, animated and moving.But I can't get the array to draw itself on a coordinate I spcify. I drew it with a `Vector2` and whatever values I put to it the drawn position never changes. Here is my invader class:

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;

namespace SpaceInvaders
{
    class botInvaders
    {

        public botInvaders()
        {

        }

        public static Texture2D botInvaderTex;
        public static Rectangle botInvaderHitBox;
        public static Vector2 botInvaderPos = new Vector2(0, 24), botInvaderOrigin;

        int botInvaderCurrentFrame = 1, botInvaderFrameWidth = 52, botInvaderFrameHeight = 88;

        float spriteTimer = 0f, spriteInterval = 100;

        public static Rectangle[,] botInvadersRect;
        int invaderRows = 5, invaderCollumns = 10;
        String botInvadersDirection = "RIGHT";
        public static Color invadersColor = Color.White;

        public void LoadContent(ContentManager Content)
        {
            botInvaderTex = Content.Load<Texture2D>(".\\gameGraphics\\gameSprites\\botInvaders\\normalInvaders\\invaderShip1"); // invaderShip1
            botInvadersRect = new Rectangle[invaderRows, invaderCollumns];
            for (int r = 0; r < invaderRows; r++)
            {
                for (int c = 0; c < invaderCollumns; c++)
                {
                    botInvadersRect[r, c].Width = botInvaderFrameWidth;
                    botInvadersRect[r, c].Height = botInvaderTex.Height;
                    botInvadersRect[r, c].X = 70 * c;
                    botInvadersRect[r, c].Y = 70 * r;
                }
            }
        }

        public void Update(GameTime gameTime)
        {
            botInvaderHitBox = new Rectangle(botInvaderCurrentFrame * botInvaderFrameWidth, 0, botInvaderFrameWidth, botInvaderFrameHeight);
            botInvaderOrigin = new Vector2(botInvaderHitBox.X / 2, botInvaderHitBox.Y / 2);

            spriteTimer += (float)gameTime.ElapsedGameTime.Milliseconds;

            if (spriteTimer > spriteInterval)
            {
                botInvaderCurrentFrame++;
                spriteTimer = 0f;
            }

            if (botInvaderCurrentFrame == 2)
            {
                botInvaderCurrentFrame = 0;
            }

            botInvaderHitBox = new Rectangle(botInvaderCurrentFrame * botInvaderFrameWidth, 0, botInvaderFrameWidth, botInvaderFrameHeight);
            botInvaderOrigin = new Vector2(botInvaderHitBox.Width / 2, botInvaderHitBox.Height / 2);

            int m_RightSide = 800;
            int m_LeftSide = 0;

            for (int r = 0; r < invaderRows; r++)
            {
                for (int c = 0; c < invaderCollumns; c++)
                {
                    if (botInvadersDirection.Equals("RIGHT"))
                    {
                        botInvadersRect[r, c].X = botInvadersRect[r, c].X + 1;
                    }

                    if (botInvadersDirection.Equals("LEFT"))
                    {
                        botInvadersRect[r, c].X = botInvadersRect[r, c].X - 1;
                    }
                }
            }

            String botInvadersChangeDirection = "N";

            for (int r = 0; r < invaderRows; r++)
            {
                for (int c = 0; c < invaderCollumns; c++)
                {
                    if (botInvadersRect[r, c].X + botInvadersRect[r, c].Width > m_RightSide)
                    {
                        botInvadersDirection = "LEFT";
                        botInvadersChangeDirection = "Y";
                    }

                    if (botInvadersRect[r, c].X < m_LeftSide)
                    {
                        botInvadersDirection = "RIGHT";
                        botInvadersChangeDirection = "Y";
                    }
                }

                if (botInvadersChangeDirection.Equals("Y"))
                {
                    for (int c = 0; c < invaderCollumns; c++)
                    {
                        botInvadersRect[r, c].Y = botInvadersRect[r, c].Y + 3;
                    }
                }
            }
        }

        public void Draw(Texture2D texture, Vector2 position, Rectangle[,] destinationRect, Nullable<Rectangle> sourceRect, Color color, float rotation, Vector2 origin, SpriteEffects effects, float scale, SpriteBatch spriteBatch)
        {
            for (int r = 0; r < invaderRows; r++)
            {
                for (int c = 0; c < invaderCollumns; c++)
                {
                    // spriteBatch.Draw(botInvaderTex, botInvaderPos, botInvadersRect[r, c], botInvaderHitBox, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0);
                    spriteBatch.Draw(botInvaderTex, botInvadersRect[r, c], botInvaderHitBox, Color.White);
                }
            }
        }
    }
}

```

I initialized the class and drew it like this in Game1:

```
botInvader.Draw(botInvaders.botInvaderTex, botInvaders.botInvaderPos, botInvaders.botInvadersRect, botInvaders.botInvaderHitBox, Color.White, 0f, botInvaders.botInvaderOrigin, SpriteEffects.None, 1.0f, spriteBatch);

```

What should I change so that the array draws at `0, 24`, since it doesn't...

# Answer
> 0 votes
Should have been: `botInvadersRect[r, c].Y = (70 * r) + 24;`

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


# Question
Title: How do I change a Unity 4.6 Sprite's textureRect at runtime?
I'm using Unity 4.6, and I've made a sprite like this:

```
    AtlasFrameData frame = _testAtlas.GetFrameByIndex(0);
    Rect spriteRect = new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y);
    Sprite _theSprite = Sprite.Create(_testAtlas.AtlasTexture, spriteRect, new Vector2(0, 0));

```

The texture is an atlas, and I have a bunch of data read in from an XML file telling me where the frames are. I want to do this in Update():

```
    AtlasFrameData frame = _testAtlas.GetFrameByIndex(_currentFrame);
    Rect spriteRect = new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y);
    _theSprite.textureRect = spriteRect;

```

But I'm unable to do this since .textureRect is readonly. I could create a new Sprite each frame, but I suspect this is not going to perform well with tons of Sprites.

# Answer
> 0 votes
Got it. You create all the Sprites up front and keep them. Each Sprite object takes about 500 bytes of RAM, and you just set the Image.Sprite attribute to the frame you want.

```
Sprite[] _animationFrameSprites;
private Image _theImage;
private GameObject _theObj;
private Vector3 _theRootPosition;

void Start()
{
    AtlasFrameData frame;
    for (int i = 0; i < _testAtlas.NumberOfFrames; i++)
    {
        frame = _testAtlas.GetFrameByIndex(i);
        Rect spriteRect = new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y);
        _animationFrameSprites[i] = Sprite.Create(_testAtlas.AtlasTexture, spriteRect, new Vector2(0, 0));
    }
}

void Update()
{
    _currentFrame++;
    if (_currentFrame >= _testAtlas.NumberOfFrames)
    {
        _currentFrame = 0;
    }

    AtlasFrameData frame = _testAtlas.GetFrameByIndex(_currentFrame);
    _theObj.transform.position = _theRootPosition + new Vector3(frame.Offset.x, frame.Offset.y, 0);

    _theImage.sprite = _animationFrameSprites[_currentFrame];
    _theImage.SetNativeSize();
}

```

---
Tags: unity, textures
---


# Question
Title: How can I acquire marketing and sales data for games?
I need to evaluate a marketing perspective for a videogame in order to predict its income, sold units, etc. Since this sounds like quite a bit of an impossible task, I thought I could collect some statistic for similar games in order to have an idea.

Is there a way which I could figure out selling statistics about games on specific platform? For example collect statistic for game *xyz* available on Steam platform or game *abc* available on HumbleBundle.

I think that could be a good practice to achieve this goal.

EDIT: recently was published SteamSpy, which offers a lot of statistics about games on Steam platform.

# Answer
You generally need to pay the market research corporations for this information. Often quite a lot of money, as well. Even then what you'll get is generally the perspective of retail markets, and not the perspective of the individual studios responsible for the games.

Some basic, high-level information is usually available (for example, news outlets will report on the NPD charts). But often you have to purchase the detailed reports. Sales breakdowns from individual companies, such as Valve, may not be available at all. If they are you'll likely need to either dig through lots of random news reports to assemble the data, read investor reports if available, or (again) pay somebody to do this for you.

What you are trying to do (predict the sales of a game based on previous data) is a hard problem even *with* good data (past performance is no guarantee of future results, just like with the stock market). It's going to be very hard to do on the cheap.
> 8 votes

# Answer
As to complete what Josh already said, here I'm posting some data I was able to fast gather on the web. They are related to some of the most famous indie games released in the last years.

and here's a take from a game that did well but didn't hit the lottery: Cardinal Quest
> 6 votes

---
Tags: marketing
---


# Question
Title: Texture Region drawing issue with LibGDX
I am currently moving my old slick2d project to libgdx. I have created a custom AnimationExt class that extends Animation to which I added a draw method. The Animation's frames are actually TextureRegion so I draw current frame TextureRegion. Here is the code, it's pretty simple.

```
    public class AnimationExt extends Animation {

    float stateTime=0;
    TextureRegion currentFrame=null;
    boolean isStopped=false;

    public void draw(SpriteBatch batch,float x, float y,int originX, int originY, float xscale, float yscale, boolean hMirror, boolean vMirror, float angle, boolean clockwise){
        if(isStopped==false){
            stateTime += Gdx.graphics.getDeltaTime();
            currentFrame=getKeyFrame(stateTime);

        }else{
            currentFrame=getKeyFrame(stateTime);
        }
        batch.draw(currentFrame, x-currentFrame.getRegionWidth()/2, y-currentFrame.getRegionHeight()/2,currentFrame.getRegionWidth(),currentFrame.getRegionHeight());
        }

    public AnimationExt(float frameDuration,
            Array<? extends TextureRegion> keyFrames, int playType) {
        super(frameDuration, keyFrames, playType);
    }
}

```

This code works well. BUT when I add parameters to the batch.draw method (originX, originY, scaleX, scaleY, angle, clockwise) like this:

```
batch.draw(currentFrame, x-currentFrame.getRegionWidth()/2, y-currentFrame.getRegionHeight()/2,originX,originY,currentFrame.getRegionWidth(),currentFrame.getRegionHeight(),xscale,yscale,angle,clockwise);

```

The drawing method goes crazy: it draws the texture rotated to -90 (whereas the angle I entered was 0) and it the width and height are inverted. To fix this I had to do change the code like that :

```
batch.draw(currentFrame, x+currentFrame.getRegionWidth()/2, y-currentFrame.getRegionHeight()/2,originX,originY,currentFrame.getRegionHeight(),currentFrame.getRegionWidth(),xscale,yscale,90+angle,clockwise);

```

But I don't want to keep this code as I'm pretty sure it's weird and I want to know why does the drawing method have such a weird behaviour when adding more parameters. By the way, I'm using the very last nightly builds of 17th June.

# Answer
What values are you using for originX, originY, scaleX, scaleY? maybe you are using wrong values for originX and originY. The origin is bottom left corner of the textureregion as stated in the docs. To set the origin to the center of the texture set

```
originX = currentFrame.getRegionWidth()/2;
originY = currentFrame.getRegionHeight()/2;

```

Hope this helps.

There is also a thread with a question related to the draw function, maybe it will help you.
> 1 votes

---
Tags: textures, libgdx
---


title: Multiple weapons for android game

text:
# Question
Title: Multiple weapons for android game
I am trying to make a 3D game for android using the Rajawali engine to render the 3D graphics and blender for designing my models(exporting as `.md2`), and I want my character to be able to change weapons, armor, helm, etc.

Rendering every possible animation would be too much: if I had 10 different weapons, 10 armor and 10 helm, I would have to create 1000 animations with every possible equipment and if I add boots to list it would be even worse.

I read somewhere you can use bones for this; but in Android, I only get the object itself to work with.

Does anyone has an idea how i can solve this? If I make the weapon a different object how do I parent it to my models in my game?

# Answer
> 1 votes
MD2 files are just mesh frame arrays. There is no skeleton. Actions are just mesh frame sequences in the array.

You can copy the character's md2 file for each weapon. Carefully replace the character mesh with a positioned weapon mesh for each action sequence frame.

While labor intensive, this approach allows you to give the weapon movement much more realism than the usual "welded to skeleton" effect.

Rajawali has the usual parenting (addChild) and visibility settings for objects, so managing the weapons is easy.

# Answer
> 0 votes
for a similar requirement in a prototype (all be it on unity for desktop) but i think the logic, planning & structure should stay the same.

1. i was able to create a parent object for each class of weapon with different animations.
2. then i added all the different appearance of the different models as children of that parent object and simply animated the class parent objects
3. finally you hide all of the irrelevant models and only show the necessary one, eg what the player has in their hands

the overall structure was many different models of only a few different types, but they all shared the same animations within each type

```
2h Sword Container 'Parent'
 - Claymore
 - Broadsword
 - Frostmourne
 - Ice

Dagger Container 'Parent'
 - Sting
 - Heartseeker
 - Perditions Blade

```

---
Tags: android, 3d, animation, blender
---


# Question
Title: How to transform Unity terrain coordinates
My map creator created some terrain in Unity, but all my scripts are based on the X-Y axis. Is there an easy and smart way to transform them into Z-Y, or do I have to change all the vector variables to Vector3 and move the coordinates to (0,Y,Z)?

# Answer
Since you're using Unity's terrain, you'll have to make some sacrifices. Unity's terrain is semi-procedural and stuck in the Z-Y plane, so you'll either have to:

* export the terrain data and import it into a third party terrain generator (I think Blender has a plugin for that) and then repaint the textures onto it.
* or change the scripts around to be in "top down" form.
* find something on the store that mimics Unity's terrain generator and supports what you need.
> 0 votes

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


# Question
Title: Find index of GameObject in array of GameObjects
In my script, i have declared an array of GameObjects like this:

```
public GameObject[] go;ld object name. `String temp;`

```

Also, i have a temporary variable to ho Then, i assigned objects to elements in Inspector.

I'm using Raycasting to find which object was clicked. Block of code for handling Raycast:

```
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity,layerMask);

        if (hit) {
            temp=hit.collider.gameObject.name;
            index=ArrayList.IndexOf(go,GameObject.Find (temp));

                }

```

Ray casting works well. It will print object name if i insert a Debug.Log. However, what i want to do is, find the GameObject's index in the array "go". I need this index because i have another boolean array isSelect\[\] which, has a property that needs to be set to true when the corresponding GameObject is selected.

With the IndexOf code above, i get the following error:

```
An object reference is required to access non-static member `System.Collections.ArrayList.IndexOf(object)

```

What changes do i need to make to this code?

# Answer
> 1 votes
It worked after i replaced

```
index=ArrayList.IndexOf(go,GameObject.Find (temp));

```

with

```
index=System.Array.IndexOf(go,GameObject.Find (temp));

```

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


# Question
Title: Phone complains that identical GLSL struct definition differs in vert/frag programs
When I provide the following struct definition in linked frag and vert shaders, my phone (Samsung Vibrant / Android 2.2) complains that the definition differs.

```
struct Light {
    mediump vec3 _position;
    lowp vec4 _ambient;
    lowp vec4 _diffuse;
    lowp vec4 _specular;
    bool _isDirectional;
    mediump vec3 _attenuation; // constant, linear, and quadratic components
};

uniform Light u_light;

```

I know the struct is identical because its included from another file. These shaders work on a linux implementation and on my Android 3.0 tablet. Both shaders declare "precision mediump float;"

The exact error is:

```
Uniform variable u_light type/precision does not match in vertex and fragment shader

```

Am I doing anything wrong here, or is my phone's implementation broken? Any advice (other than file a bug report?)

# Answer
> 0 votes
I'm not going to flag this as the correct answer, but I have worked around this by avoiding this particular struct. Pretty lame.

# Answer
> 1 votes
The reason is due to a bug in the driver (or an overlooked gotcha in the GLSL language?). Your vertex shader uses some of the struct members, your fragment shader uses a different set of the struct members, and the drivers ends up creating 2 different types by independently eliminating the unused uniforms from the struct type in both shaders which cause them to differ when linked together as the final step. To work around this you have to split your struct in 2 (one for vertex, one for fragment) or pass the pixel shader data as varying data (wasteful).

---
Tags: android, opengl-es, shaders, glsl
---


title: Transparency on pixel level?

text:
# Question
Title: Transparency on pixel level?
I'm using java and I do pixel-by-pixel rendering (a pixel array from an ARGB BufferedImage). So a color is 0xAARRGGBB. Now how can I render a transparent color? I guess that I should manipulate the existing pixel and not overwrite it. I can make color addition simply:

```
public static int additiveColor(int c1, int c2) {
        int red = (c1 & 0x00ff0000) + (c2 & 0x00ff0000);
        int grn = (c1 & 0x0000ff00) + (c2 & 0x0000ff00);
        int blu = (c1 & 0x000000ff) + (c2 & 0x000000ff);
        return 0xff000000 + (red > 0x00ff0000 ? 0x00ff0000 : red) + (grn > 0x0000ff00 ? 0x0000ff00 : grn) + (blu > 0x000000ff ? 0x000000ff : blu);
    }

```

So to set a pixel to a sum of two colors I just do this:

```
pixels[i] = additiveColor(c1, c2);

```

How can I do transparency?

# Answer
> 1 votes
### You want linear interpolation using the alpha channel of the incoming (source) pixel.

This goes by different names in different APIs (`mix (...)` in OpenGL, `lerp (...)` in D3D). No matter what you call it, it boils down to the following:

```
public static int alpha_blend(int c1, int c2) {
    int a1 = (c1 & 0xff000000) >>> 24;
    //int a2 = (c2 & 0xff000000) >>> 24; // Do not need for traditional alpha blending

    int r1 = (c1 & 0x00ff0000) >> 16;
    int r2 = (c2 & 0x00ff0000) >> 16;

    int g1 = (c1 & 0x0000ff00) >> 8;
    int g2 = (c2 & 0x0000ff00) >> 8;

    int b1 = (c1 & 0x000000ff);
    int b2 = (c2 & 0x000000ff);

    float src_alpha = ((float)a1) / 255.0f;

    int red   = (r1 * src_alpha) + (r2 * (1.0f - src_alpha));
    int green = (g1 * src_alpha) + (g2 * (1.0f - src_alpha));
    int blue  = (b1 * src_alpha) + (b2 * (1.0f - src_alpha));

    return (a1 << 24) | (red << 16) | (green << 8) | blue;
}

```

You might need some casts to make Java happy, I would not consider this more than pseudo-code to give you an idea of what needs to happen.

---
Tags: java, rendering, per-pixel
---


title: Sprite not drawing at correct position

text:
# Question
Title: Sprite not drawing at correct position
I have a texture with 20x20 pixels.

Consider this piece of code:

```
public override void Draw(GameTime gameTime)
{
    spriteBatch.Draw(texture,Position * 20,null, Color.White, 0f, new Vector2(texture.Width / 2, texture.Height / 2),1, SpriteEffects.None,1);
    base.Draw(gameTime);
}

```

Position=(0,0)

But when I use `new Vector2(10,10)` in the following code

```
public override void Draw(GameTime gameTime)
{
    spriteBatch.Draw(texture,Position * 20+new Vector2(10,10),null, Color.White, 0f, new Vector2(texture.Width / 2, texture.Height / 2),1, SpriteEffects.None,1);
    base.Draw(gameTime);
}

```

It draws at the correct position. How can I fix this?

# Answer
> 0 votes
The line we're interested in is

```
Position * 20

```

which, if Position is (0,0), is equal to (0,0)

and you say it behaves correctly for

```
Position * 20 + new Vector2(10,10)

```

which is equal to (10,10)

I'm guessing that the problem is a misunderstanding of order of operation. Adding parenthesis to show what happens first, we would have:

```
(Position * 20) + new Vector2(10,10)

```

# Answer
> 0 votes
This is a debugging issue. The image gets drawn where you are telling it to be drawn. The problem is you are not telling it to draw in the correct place. Use the debugger to examine `Position` when you enter the `Draw()` method. My guess is that `Position` will not have the value that you are expecting. If this is the case, look through your code, and find where `Position` is being set, or where it is being changed, and make sure those bits of code are doing what they are suppose to do.

# Answer
> 0 votes
It's unclear what you're *asking*, but based on everything you *stated* I don't see any issues.

Position is `(0, 0)`, the texture dimensions are `20 x 20` and the origin which you specified in the `Draw` method is `new Vector2(texture.Width / 2, texture.Height / 2)`.

What I see in the screenshot appears to be correct, with the top left corner of the texture being at `(0, 0)` after specifying its origin to be `(10, 10)` and moving it by `(10, 10)`.

---
Tags: sprites
---


title: Game info file? LibGDX android

text:
# Question
Title: Game info file? LibGDX android
In my app I need a file that I can keep settings like: TutorialSkip: True or AppDev: False and other info. How can I make this file and prevent users editing it?

This has to work in the Core folder for my project as it should work with android windows and ios.

# Answer
> 0 votes
A good way to achieve this is using **Preferences**. Follow this tutorial for more information. Good luck.

---
Tags: android, libgdx
---


# Question
Title: What is the easiest way to make an object follow the edge of a sprite?
I have a rounded rectangle sprite and another sprite that's just a circle. I want the center of the circle to follow the edge of the rounded rectangle. Is there any easy way to accomplish this task? I've seen other answers that talk about curve and AI predictive algorithms, but they all seem more complicated to implement that for my current needs. Is using these algorithms necessary for what I'm trying to do, or is there an easier way to make one sprite follow the edge of another?

# Answer
> 1 votes
You can use `Path2d` to define the outer edge of your rounded rectangle. This actually creates a `Shape`. To turn this into something you can use, `FlatteningPathIterator` can be called to create a list of points that can be used to step along the path. You can use this information to draw your circle as it progresses around your progress bar.

Here is a good example of what you are after. FlatteningPathIterator

# Answer
> 0 votes
assuming by sprite you mean that it is an image (loaded from a bitmap):

i would iterate through the pixels in the image, and identify the ones on the edge (adjacent to a transparent pixel) (or load an identical black and white hollow rectangle image showing only the edge points for easier identification) log those Points into an array by starting at one point remove it and then move to an adjacent edge point. get the position the image is displayed at offset the list co-ords by the image position. you then have a list of points for your circle to move through.

that is the simplest way to do it that i know of (dont personally use libgdx).

if the image is moving (animated) apply the offset to the array points just before you display so you dont have to reload the array each time.

there are probably better ways to do it, but this is what comes to mind for me. you could reuse the code to generate paths of any shape by drawing them in paint.

# Answer
> 0 votes
If you're looking for a really simplistic approach, here's one I've used in the past:

* Create an object that has both sub-objects (rectangle and circle)
* Create a getter/setter pair for x/y coordinates on your object
* When you move the object by calling `setX(x)`, it sets the rectangle's `x` coordinate to `x`, and the circle's `x` coordinate to `x + a` where `a` is the distance from the center of the circle to the rectangle corner.

You can do something similar for the y coordinate; essentially, you're creating a wrapper object and setting coordinates manually to some offset (so the circle is always positioned correctly relative to the rectangle).

# Answer
> 0 votes
What I would likely do is convert the rectangle to a `Pixmap`, then, assuming the rectangle has a solid single color border (with a different color than the rest of the rectangle), I would simply iterate through the pixels in the `Pixmap` looking for the border color and save all the positions to an array. Then all you would have to do is periodically set the circle's position to the next point in the array, looping (ideally the points would be relative to the center of the rectangle so the circle would stay with the rectangle even if it moved).
To keep the circle moving in one direction around the rectangle instead of jumping you would have to create a search algorithm that moves, for example, first left along the top of the rectangle (assuming the border is the top pixel) then down (scanning to half the rectangles width so as to get the full rounded corner), then right (along the bottom pixel), and finally back up. Now this scanning technique might not fit your exact needs, but take it as a starting point.

---
Tags: java, physics, libgdx, animation, sprites
---


# Question
Title: Where should I put the SDL_Renderer* using the ECS with SDL2 and C++?
So I'm still learning about ECS (Entity Component System) and whenever I'm thinking about the architecture and actual implementation, I just can't figure out where should I put the SDL\_Renderer\*.

So far what I've learned is that the Entity class should have its own unique ID, there should be a Component and System class and things like RenderComponent and RenderSystem should be derived from them. RenderComponent should contain all the data and the RenderSystem should contain the actual algorithms (correct me if I'm wrong so far).

I'm using C++ and SDL2 and I don't know how about you guys but I never really used more than one SDL\_Renderer and I'm not intending to do so either. I always just create a renderer for the window and copy everything to that one renderer and than I present that renderer to the screen. So my questions are:

* In an ECS design like I explained above, where should I put my SDL\_Renderer?
* What should the RenderComponent, and RenderSystem, contain?

# Answer
> 4 votes
If you only have a single SDL\_Renderer, it should be managed outside of the ECS code and just passed to the rendering system when you call it to render the visual data for each entity. In this way it's like you are associating your single SDL\_Renderer with all renderable entities. If for some reason you had multiple, differently configured SDL\_Renderer objects that different sets of entities used, then it might be useful to represent SDL\_Renderer objects as entities themselves (by making something like a RendererComponent for those entities that stores a pointer to a SDL\_Renderer object). You would then be able to store the ID of these renderer entities in the visual data component of each renderable entity so that the rendering system can get the right renderer needed to render each entity.

EDIT: To clarify my first comment, here is some code:

```
void RenderingSystem::Update(SDL_Renderer *renderer)
{
    for (int i = 0; i < this->GetEntityCount(); ++i)
    {
        Entity *entity = this->GetEntity(i);

        SpatialComponent *spatialComponent = entity->GetComponent<SpatialComponent>();
        VisualComponent *visualComponent = entity->GetComponent<VisualComponent>();

        SDL_Rect dstrect = visualComponent->srcrect;
        dstrect.x = spatialComponent->positionX;
        dstrect.y = spatialComponent->positionY;
        SDL_RenderCopy(
            renderer,
            visualComponent->texture,
            &visualComponent->srcrect,
            &dstrect
        );
    }
}

```

---
Tags: c++, architecture, entity, sdl2
---


# Question
Title: Rectangle collision in SDL2 partially allowing sliding C++
I am working on a game in SDL2, in which the player needs to be able to slide along walls, but NOT go through them. I've read up on things like Quadtrees, and this stackoverflow question https://stackoverflow.com/questions/2656943/2d-platformer-collision-problems-with-both-axes, but I have no idea how to implement Quadtrees (I'm a relative beginner still to C++) and no idea on how to check how much overlap there is. I tried using SDL2's collision functions, but to no avail. Here are my collision functions

**main.cpp**

```
//At the top of the program, initialized as global
//variables are the isCollidingYAxis/isCollidingXAxis variables,
//and those are set to false.
bool check_collision(SDL_Rect a, SDL_Rect b){
    int leftA, leftB;
    int rightA, rightB;
    int topA, topB;
    int bottomA, bottomB;

    leftA = a.x;
    rightA = a.x + a.w;
    topA = a.y;
    bottomA = a.y + a.h;

    leftB = b.x;
    rightB = b.x + b.w;
    topB = b.y;
    bottomB = b.y + b.h;

    if(rightA <= leftB || leftA >= rightB){
        if(isCollidingYAxis){
            isCollidingYAxis = false;
            return false;
        } else {
            isCollidingXAxis = true;
            return false;
        }
    }

    if(bottomA <= topB || topA >= bottomB){
        if(isCollidingXAxis){
            isCollidingXAxis = false;
            return false;
        } else {
            isCollidingYAxis = true;
            return false;
        }
    }
    return true;
}

void reset_collision()
{
    isCollidingXAxis = false;
    isCollidingYAxis = false;
}

//further down, I call the above functions from my player class...
void Player::move_player(std::vector<SDL_Rect> objectsWeHit)
{
    playerPositionX += playerVelocityX;
    playerPositionY += playerVelocityY;
    pCollider.x = playerPositionX;
    pCollider.y = playerPositionY;

    for(int x = 0; x < vectorOfRectangles.size(); x++){
        if(check_collision(pCollider, objectsWeHit[x])){
            if(isCollidingXAxis){
                playerPositionX -= playerVelocityX;
                pCollider.x = playerPositionX;
                std::cout << "Collision detected on the X axis!" << std::endl;
                reset_collision();
            }
            if(isCollidingYAxis){
                playerPositionY -= playerVelocityY;
                pCollider.y = playerPositionY;
                std::cout << "Collision detected on the Y axis!" << std::endl;
                reset_collision();
            }
        }
    }
}

```

My collision detection functions are similar to lazy foo production's collision detection. The tutorial that I based my function off of can be found here: http://lazyfoo.net/tutorials/SDL/27\_collision\_detection/index.php. In case its not obvious, I am using a vector to store rectangles, and I'm positive that part is okay. The problem right now is that only the X axis collision detection works, and not the Y axis. Meaning I can go through the top/bottom of the rectangle and not the left/right. I can, however, slide along the left/right sides of the rectangle, which is the desired behaviour. The complete program can be found here: https://bpaste.net/show/1715097a16e1. I'm at a complete loss, so any help is appreciated!

# Answer
What you need to do to implement sliding:

1) find the exact location of collision

2) find the normal of the collision

3) move the object to the location of collision

4) set the velocity of object opposite of the collision normal to 0; (or you need projection if you are working with non axis aligned stuff)

5) move the object again using the new adjusted velocity using the remaining time left. You might need to run your collision and resolution algorithm again.
> 1 votes

---
Tags: c++, collision-detection, sdl, sdl2
---


# Question
Title: Alternative Font loaders in Monogame Framework
While working on projects of mine, I have been finding that it is a huge pain to switch operating systems just to create a simple spritefont when using Monogame. I saw that the Nuclex Framework can load fonts which are clearer/sharper, and they can be used in a Monogame project as well. They load fonts using the FreeType library, which is very multiplatform and is used widely. Is there a fairly simple way to use the FreeType library or another library to render text suitable for use in a Monogame project, as an xnb file?

# Answer
From my understanding a spritefont is essentially a collection of sprites where each letter translates to a coordinate on a spritesheet, such as the following:

You can do this manually, of course, but it would be a pain to check each coordinate. You can use BMFont to do the conversion for you, which creates an image such as the one above, followed by an xml file with coordinates to each letter.

I've never done it with MonoGame, but you can find a tutorial here

As far as what you said about needing to switch operating systems to create the file, what do you mean? You can create a content project in MacOS and Windows. Also, MonoGame has been working on the new pipeline using the new Pipeline.exe and related tools
> 1 votes

---
Tags: sprites, monogame, fonts
---


# Question
Title: Compiling the Latest MonoGame.dll on GitHub
I've been searching for hours, but still I cannot find "How to compile the latest MonoGame source code from GitHub".

I have tried cloning the GitHub project (develop branch) and I've been looking for the solution that can be used so it will open on Xamarin studio and compile directly, but I have no luck and I don't know if it is the right procedure to get the latest MonoGame library.

Can anyone please help me cite the steps and procedures needed to compile the latest MonoGame source code from GitHub?

# Answer
If you don't need to modify any source, I would recommend you instead get a nightly build and use that instead.

**Installing an mpack in Xamarin Studio**

This should be the easiest method to get MonoGame working in Xamarin Studio. Go to the downloads page and click on "MonoGame for MonoDevelop".

This will download a .mpack that you can install directly by going to the "AddIn's Manager" in Xamarin Studio. Choose "Install from file" and locate the .mpack and you should be good to go

**Using .dlls from a nightly build**

Go to the downloads page and then click on "MonoGame for Visual Studio" under Development Builds. That will get you the latest build from the MonoGame TeamCity page.

You can then unzip the executable and grab the .dll files which will be in the folder "Assemblies" and use them as references in your Xamarin Studio project.

if you really want to compile it, it's not too bad either.

**Compiling From Source**

Either fork the MonoGame Develop repository or download the project as a .zip from GitHub and run ProtoBuild.exe

That will create all of the .csproj files for each platform, which you can open in Xamarin Studio to use as library projects.
> 2 votes

---
Tags: monogame, source-code, git
---


# Question
Title: How do I raycast to detect which hexagonal tile was clicked?
I want to detect the hexagonal tile a unit is on upon clicking on the unit. I was thinking of using a ray cast I can't get it to work.

I'm trying to get the raycast to shoot from the bottom of the unit and change the material of the collided object.

```
if (Input.GetMouseButtonDown (0)) {

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if(Physics.Raycast(ray, out hit)){

        Debug.Log (hit);

        string hitTag = hit.transform.tag;

        if(hitTag == "player"){

            if(Physics.Raycast(user.transform.position,Vector3.down,10)){

                Debug.Log ("I'm on something!");

                hit.collider.renderer.material.color = Color.red;

            }
        }
    }
}

```

What might be going wrong?

# Answer
> 1 votes
If in general clicking the unit has no other use than selecting the tile, you could simply put the units on the Ignore Raycast layer so you can select directly the tile, in this case you can also attach a script on the tiles with the OnMouseDown function. If you want to access, in that way, the unit, you could maintaing of structure describing the tiles (so also where are the units) and update it when necessary.

I'm not sure what user is in your code, but I think that you can create a vector like:

```
Vector3 rayStartPoint = new Vector3(user.tranform.position.x, -5, user.transform.position.z)

```

(assuming that everything at -5 y is under the field) and then:

```
Physics.Raycast(rayStartPoint, Vector3.up, 10).

```

I think your tiles are on a field so, also in this case, you have to set the field layer on Ignore Raycast otherwise the first thing to be hit will be the field.

If you want to use only a single raycast you could just set all your tiles to a specific layer and then make so that the raycast hits only that layer, for that specific operation:

```
Physics.Raycast(ray, out hit, layerMask)

```

Layers

# Answer
> 0 votes
You are performing two raycasts, but only storing the result of the first one in hit. So the renderer you access to change material color to red is the renderer of the player, not the renderer of the tile.

Add 'out hit' as a parameter to your second Physics.Raycast call:

```
Physics.Raycast(user.transform.position,Vector3.down, out hit, 10);

```

---
Tags: unity, collision-detection, raycasting, tiles
---


title: Transparency using HLSL in XNA

text:
# Question
Title: Transparency using HLSL in XNA
I currently working on Depth Data on Kinect SDK v1.8 on XNA and I wanna show an Image Inside the Depth view of Human body. the image below is just an example of what I wanna do :

http://static.gamespot.com/uploads/original/1535/15354745/2429785-screen4.jpg

for Depth View, this is what I've done :

```
void kinectSensor_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
{
    using (DepthImageFrame depthImageFrame = e.OpenDepthImageFrame())
    {
        if (depthImageFrame != null)
        {
            short[] pixelsFromFrame = new short[depthImageFrame.PixelDataLength];

            depthImageFrame.CopyPixelDataTo(pixelsFromFrame);
            byte[] convertedPixels = ConvertDepthFrame(pixelsFromFrame, ((KinectSensor)sender).DepthStream, 640 * 480 * 4);

            Color[] color = new Color[depthImageFrame.Height * depthImageFrame.Width];
            kinectRGBVideo = new Texture2D(graphics.GraphicsDevice, depthImageFrame.Width, depthImageFrame.Height);

            // Set convertedPixels from the DepthImageFrame to a the datasource for our Texture2D
            kinectRGBVideo.SetData<byte>(convertedPixels);
        }
    }
}

// Converts a 16-bit grayscale depth frame which includes player indexes into a 32-bit frame
// that displays different players in different colors
private byte[] ConvertDepthFrame(short[] depthFrame, DepthImageStream depthStream, int depthFrame32Length)
{
    int tooNearDepth = depthStream.TooNearDepth;
    int tooFarDepth = depthStream.TooFarDepth;
    int unknownDepth = depthStream.UnknownDepth;
    byte[] depthFrame32 = new byte[depthFrame32Length];

    for (int i16 = 0, i32 = 0; i16 < depthFrame.Length && i32 < depthFrame32.Length; i16++, i32 += 4)
    {
        int player = depthFrame[i16] & DepthImageFrame.PlayerIndexBitmask;
        int realDepth = depthFrame[i16] >> DepthImageFrame.PlayerIndexBitmaskWidth;

        // transform 13-bit depth information into an 8-bit intensity appropriate
        // for display (we disregard information in most significant bit)
        byte intensity = (byte)(~(realDepth >> 4));

        if (player == 0 && realDepth == 0)
        {
            // white
            depthFrame32[i32 + RedIndex] = 255;
            depthFrame32[i32 + GreenIndex] = 255;
            depthFrame32[i32 + BlueIndex] = 255;
        }
        else if (player == 0 && realDepth == tooFarDepth)
        {
            // dark purple
            depthFrame32[i32 + RedIndex] = 66;
            depthFrame32[i32 + GreenIndex] = 0;
            depthFrame32[i32 + BlueIndex] = 66;
        }
        else if (player == 0 && realDepth == unknownDepth)
        {
            // dark brown
            depthFrame32[i32 + RedIndex] = 66;
            depthFrame32[i32 + GreenIndex] = 66;
            depthFrame32[i32 + BlueIndex] = 33;
        }
        else
        {
            // tint the intensity by dividing by per-player values
            depthFrame32[i32 + RedIndex] = (byte)(intensity >> IntensityShiftByPlayerR[player]);
            depthFrame32[i32 + GreenIndex] = (byte)(intensity >> IntensityShiftByPlayerG[player]);
            depthFrame32[i32 + BlueIndex] = (byte)(intensity >> IntensityShiftByPlayerB[player]);
        }
    }

    return depthFrame32;
}

```

I'm not sure how I can get the Object inside the Depth View of the body. Update : I found out I can use HLSL to achieve this for a 3D model :

```
float4x4 World;
float4x4 View;
float4x4 Projection;
float4x4 WorldInverseTranspose;

float4 AmbientColor = float4(1, 1, 1, 1);
float AmbientIntensity = 0.1;

float3 DiffuseLightDirection = float3(1, 0, 0);
float4 DiffuseColor = float4(1, 1, 1, 1);
float DiffuseIntensity = 1.0;

float Shininess = 200;
float4 SpecularColor = float4(1, 1, 1, 1);
float SpecularIntensity = 1;
float3 ViewVector = float3(1, 0, 0);

float Transparency = 0.5;

texture ModelTexture;
sampler2D textureSampler = sampler_state {
    Texture = (ModelTexture);
    MinFilter = Linear;
    MagFilter = Linear;
    AddressU = Clamp;
    AddressV = Clamp;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float4 Normal : NORMAL0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float4 Color : COLOR0;
    float3 Normal : TEXCOORD0;
    float2 TextureCoordinate : TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
        float4 viewPosition = mul(worldPosition, View);
        output.Position = mul(viewPosition, Projection);

    float4 normal = normalize(mul(input.Normal, WorldInverseTranspose));
        float lightIntensity = dot(normal, DiffuseLightDirection);
    output.Color = saturate(DiffuseColor * DiffuseIntensity * lightIntensity);

    output.Normal = normal;

    output.TextureCoordinate = input.TextureCoordinate;
    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float3 light = normalize(DiffuseLightDirection);
    float3 normal = normalize(input.Normal);
    float3 r = normalize(2 * dot(light, normal) * normal - light);
    float3 v = normalize(mul(normalize(ViewVector), World));
    float dotProduct = dot(r, v);

    float4 specular = SpecularIntensity * SpecularColor * max(pow(dotProduct, Shininess), 0) * length(input.Color);

        float4 textureColor = tex2D(textureSampler, input.TextureCoordinate);
        textureColor.a = 1;

    float4 color = saturate(textureColor * (input.Color) + AmbientColor * AmbientIntensity + specular);
        color.a = Transparency;
    return color;
}

technique Textured
{
    pass Pass1
    {
        AlphaBlendEnable = TRUE;
        DestBlend = INVSRCALPHA;
        SrcBlend = SRCALPHA;
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

and this is my Draw Code in Game1 Class:

```
protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        DrawModelWithEffect(model, world, view, projection);

        base.Draw(gameTime);
    }

    private void DrawModelWithEffect(Model model, Matrix world, Matrix view, Matrix projection)
    {
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (ModelMeshPart part in mesh.MeshParts)
            {
                part.Effect = effect;
                effect.Parameters["World"].SetValue(world * mesh.ParentBone.Transform);
                effect.Parameters["View"].SetValue(view);
                effect.Parameters["Projection"].SetValue(projection);
            }
            mesh.Draw();
        }
    }

```

My problem is that I want to use this same idea to create a transparency between two 2D Images.

Is there something like this out there for 2D? If so where can I find it.

# Answer
> 0 votes
I wrote HLSL code for transparency and then I will transparent one image inside the body and another image used for my foreground :

```
sampler stream : register(s0);
sampler back : register(s1);
sampler character : register(s2);

float4 DepthToRGB(float2 texCoord : TEXCOORD0) : COLOR0
{
// We can't easily sample non-normalized data,
// Texture is a short packed stuffed into a BGRA4444 (4 bit per component normalized)
// It's not really BGRA4444 which is why we have to reverse the normalization here
float4 color = tex2D(stream, texCoord);
float4 backColor =  tex2D(back, texCoord);
float4 characterColor = tex2D(character, texCoord);

// convert from [0,1] to [0,15]
color *= 15.01f;

// unpack the individual components into a single int
int4 iColor = (int4)color;
int depthV = iColor.w * 4096 + iColor.x * 256 + iColor.y * 16 + iColor.z;

// player mask is in the lower 8 bits
int playerId = depthV % 8;

if(playerId == 0)
{
    //Not yet recognized
    return backColor * float4(1.0,  1.0,  1.0,  1.0);
}
else
{
    return backColor * characterColor;
}
}

technique KinectDepth
{
pass KinectDepth
{
    PixelShader = compile ps_2_0 DepthToRGB();
}
}

```

# Answer
> 0 votes
Keep in mind that in XNA (and all other 3D libraries), 2D *is* 3D! In XNA, sprites are just 3D planes drawn to the screen. Any shader you use in 3D will work just as well with the spritebatch. Spritebatch.Begin() has a parameter for the shader to pass in.

If I'm following you, you want to use the depth image to blend between two images. Here's what I would do:

* Render the entire scene to a RenderTarget2D
* Draw a quad to the screen using the RenderTarget2D as a texture.
* In a custom HLSL shader, sample the depth image from the Kinect to determine whether to blend between the previous texture or some other texture.

---
Tags: xna, c#, hlsl, kinect
---


title: Jump Issue(Unity3D)

text:
# Question
Title: Jump Issue(Unity3D)
This is my first character control script.
Where a cube is my player and the objective the i want to achieve with my script are
**1**.the cube moves in horizontal axis till the button is pressed once release the cube should stop(done)
**2**.the cube should has max vertical speed when the button is press the cube should move in vertical direction and try to reach the max-speed but when the button is released the cube should move at that speed continuous unless an opposite force is applied(done)
**3**.the cube should be able to jump (failed)
I want to make the cube jump but it just sticks to the ground. When gravity is turn on it jump but does not move forward and when gravity is turn off it moves forward but when pressed Jump it does not come down continuously move up. if anyone have played classic skyroads game am try to make that but a simple one without using raycast etc.

```
void FixedUpdate ()
{
    shipvelo = rigidbody.velocity;
    shipmagno = rigidbody.velocity.magnitude;

    Vector3 vel = rigidbody.velocity;
    vel.x = Input.GetAxisRaw("Horizontal") * MaxHorSpeed;

    if (Input.GetKeyDown(KeyCode.Space) && IsGrounded()){
        vel.y = jumpSpeed;
        print("I am on");
    }

    rigidbody.velocity = vel;

    rigidbody.AddForce (Vector3.forward * Input.GetAxis("Vertical") * forSpeedMul);
    rigidbody.velocity = new Vector3(Mathf.Clamp(rigidbody.velocity.x, -horizantalClamp, horizantalClamp),0,Mathf.Clamp(rigidbody.velocity.z, -VerticalClamp, VerticalClamp));
}

```

# Answer
> 1 votes
The second time you're setting the velocity of the rigidbody you pass in 0 for the y coordinate, so it will never move in the y axis.

You should really only be setting the velocity of your rigidbody when you jump (as Unity3D recommends), like so:

```
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
    Vector3 jumpVel = rigidbody.velocity + Vector3.up * jumpspeed;
    rigidbody.velocity = jumpVel;
}

```

and the rest of the movement with forces, for more realistic looking movement.

---
Tags: unity, physics
---


# Question
Title: How do components and systems relate to each other in an entity component system?
I'm trying to learn and understand the ECS (Entity Component System) so that I can create a game using this design pattern but I've got a lot of things that I still don't understand.

Lets say I've got a *PositionComponent* and a *MovementSystem* or *PhysicsSystem*. The PhysicsSystem will heavily rely on the *PositionComponent* since in order to calculate, for example a rigid body motion, it needs the x and y positions (in a 2D game) wich is contained by the *PositionComponent*.

What is the relationship between *Components* and *Systems*? How does the *MovementSystem* get the x and y values from the *PositionComponent*?

# Answer
One way for a system to know about components is by it knowing that every entity it has access to when it updates will have some combination of component objects.

For example, with a movement system:

```
void MovementSystem::Update(float deltaTime)
{
    for (int i = 0; i < this->GetEntityCount(); ++i)
    {
        Entity *entity = this->GetEntity(i);

        /* It's known that all the entities available in this system have
        at least a Velocity and Position component so they can always be gotten here */
        VelocityComponent *velocityComponent = entity->GetComponent<VelocityComponent>();
        PositionComponent *positionComponent = entity->GetComponent<PositionComponent>();

        positionComponent->x += velocityComponent->x * deltaTime;
        positionComponent->y += velocityComponent->y * deltaTime;
    }
}

```

As for how it can be guaranteed that a system will only be updating entities with the components it is interested in accessing, there are different implementations. The Artmemis Framework (originally written in Java) is an example of one way of doing it: http://gamadu.com/artemis/
> 1 votes

---
Tags: entity-system
---


title: Destroy a single list member

text:
# Question
Title: Destroy a single list member
im trying to destroy a single game object using the following script but it destroys all of them , not the ones I want. I want to destroy the ones that the transform that holds this script collides with.

It's a 2D unity3d game btw.

The script :

```
var keys : List.<Transform>;

function OnTriggerEnter2D(coll : Collider2D)
{
    for(var i = 0; i < keys.Count; i++)
    {
        Destroy (keys[i].gameObject);
    }
}

```

I hope I was clear enough , don't hesitate to ask any questions.

Thank you for your time.

# Answer
> 0 votes
I fixed this by editing my code into this :

```
function OnTriggerEnter2D(coll : Collider2D)
{
    if(coll.gameObject.tag == "Key")
        {
            Destroy (coll.gameObject);
            keysGathered ++;
        }
}

```

I didn't realise it was this simple.

Thank you for your time!

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


title: Per instance world matrix is 0.0f/NaN

text:
# Question
Title: Per instance world matrix is 0.0f/NaN
I'm trying to draw some cubes with Hardware Instancing.

---

However they don't get displayed. So I debugged my code, and found the source of the problem:

In my VertexShader, the var that has the per instance world matrix has a value of:

{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, NaN, NaN, NaN }

The weirdest thing is that it outpus NaN (Not a Number). Here's how I create my instanced buffer:

```
XMMATRIX trans[4];

trans[0] = XMMatrixTranslation(0.0f, 0.0f, 0.0f);
trans[1] = XMMatrixTranslation(0.5f, 0.5f, 0.5f);
trans[2] = XMMatrixTranslation(-0.5, -0.5, 0.5);
trans[3] = XMMatrixTranslation(0.5, -0.5f, 0.5);

//Store world matrices
for (int i = 0; i < 4; i++)
    XMStoreFloat4x4(&mIV[i].world, trans[i]);

D3D11_BUFFER_DESC instDesc;
ZeroMemory(&instDesc, sizeof(D3D11_BUFFER_DESC));
instDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
instDesc.Usage = D3D11_USAGE_DYNAMIC;
instDesc.ByteWidth = sizeof(XMFLOAT4X4) * 4;
instDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

//Create instanced buffer
HR(mDevice->CreateBuffer(&instDesc, NULL, &mBoxInstB));

```

Here's how I map the instanced data to my buffer:

```
D3D11_MAPPED_SUBRESOURCE mapSub;
mContext->Map(mBoxInstB, 0, D3D11_MAP_WRITE_DISCARD, NULL, &mapSub);

VertexI* idata = reinterpret_cast<VertexI*>(mapSub.pData);

idata = mIV;

mContext->Unmap(mBoxInstB, 0);

```

Thanks for the help! If you need some more info, write it in the comments!

# Answer
> 1 votes
The issue seem to be that you don't copy data over, you're overwriting the idata pointer with the address of mIV:

```
idata = mIV; // this changes idata to point to mIV, not copy data

```

Should be something like:

```
for(size_t i=0; i < (sizeof(mIV) / sizeof(mIV[0])); ++i){
  idata[i] = mIV[i];
}

```

Or

```
memcpy(idata, mIV, sizeof(mIV));

```

Or some other copy function to copy the whole array. I'm assuming mIV is an array and not a pointer, if it is a pointer you need to use

```
for(size_t i=0; i < 4; ++i){
  idata[i] = mIV[i];
}

```

Ideally replace 4 with a constant or variable to keep track of the number of instances.

---
Tags: directx, instancing
---


# Question
Title: Get color array with alpha for an image in java
I can get the pixel array like this:

```
int[] pixels = image.getRGB(0, 0, width, height, null, 0, width);

```

But it ignores the alpha channel, I only get the rgb (I'm reading a PNG image). How can I get the alpha channel too?

# Answer
The `getRGB()` method picks all channels, even alpha. You can extract color and alpha channels with something like:

```
Color col = new Color(pixels[pixelIndex]);

System.out.println(col.getRed());
System.out.println(col.getGreen());
System.out.println(col.getBlue());
System.out.println(col.getAlpha());

```

Depending on the image format (ABGR, ARGB), retrievieng specific channel requires some bit shift operation, and applying a mask to it. To get alpha manually, you could do `(pixels[pixelIndex] >> 24) & 0xFF`

Visit https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html for additional info about image types and methods behaviour.
> 1 votes

---
Tags: java, alpha, png
---


# Question
Title: How to keep player in the center of the screen but let him move to the edge of the map without moving camera there?
In my rpg-styled (top-down perspective) 2d game, I want my player to be at the center of the screen, while the entire world moves, giving the effect of player movement. I can make that, but my problem is at the edges of the game-world, I want the world to stop moving and the player to move.

# Answer
> 7 votes
Don't move the world. Instead move the player and add a third concept called camera which follows the player. Then you can prevent the camera moving too close to the world boundaries. When rendering, subtract camera position from everything.

---
Tags: 2d
---


# Question
Title: AABB swept collision response with voxel world
I followed this tutorial: link and I was able to make it work with 3d voxel world collisions.

But the problem I have is with collision response. I want to make player slide against the wall if he is running against it, but instead he gets stuck at each voxel edge.

That is happening because I am getting normals with AABB swept test from voxels that are a part of the wall. (Yes, I am doing broadphase check first).

In the image above is 2d representation of my problem. Voxels are black rectangles, blue one is player, red is swept check area and green lines are normals.

Possible solutions I thought of are: \- Merging voxels into bigger collision boxes based on neighbours, but I think that would cause other problems when holes appear and player size increases. \- Ignore collision normal if there is neighbour voxel along side normal. This is what I have currently in my code and works fine for sliding against walls while on ground, but fails when falling against them: http://ideone.com/xdsr2d

Because there's many voxels in that are colliding and order of collisions (the order of voxels and normals that I receive after aabb swept test) is hardly predictable neither sollution seams to be good enough.

I would appreciate any help because I've been bashing my head around this problem for quite a while.

(Also if there's anything wrong with my question do tell, this is my first time post on gamedev.stackexchange)

# Answer
TL;DR: process collisions Manhattan-distance style http://en.wiktionary.org/wiki/Manhattan\_distance, each axis independently one-by-one (move in X, then move in Y, then in Z, rince and repeat) properly rounding each axis before processing the next.

AABB / Voxel collision systems work the same way old tile-based 2D games did, you add a 3rd dimension but otherwise are identical:

For simplicity let's assume a voxel is 1x1x1 and position is the corner toward negative infinity, you need to check movement against each axis independently and properly "round" each axis after colliding them (not round as in +/-0.5 but align them a tiny bit away from the AABB grid).

Do your collisions using integers for each axis. Example here is for X check for simplicity, this should be turned into a nice for-loop. I'm using floats here but ideally with voxel collision systems fixed-point math should be used instead for easy predictability.

```
const float SMALLER = (1.0f / 16.0f); // give a Retro-style 1-pixel smaller AABB in each directions on a 16x16 pixel tile scale to fit in holes (we use 1.0f for one tile / 16.0 "pixels")
const float EPSILON = (1.0f / 1024.0f); // a value that is small enough to not show vibration on screen when bumping against the walls but remember you only have 24 bits of precision with floats.
// NOTE: use binary sizes (incl fractions) as much as possible to help stave off float rounding errors.

if(move.x != 0){
  int min_x = truncf(position.x + SMALLER);
  int max_x = truncf(position.x + AABB_SIZE.x - SMALLER);
  int min_y = truncf(position.y + SMALLER);
  int max_y = truncf(position.y + AABB_SIZE.y - SMALLER);
  int min_z = truncf(position.z + SMALLER);
  int max_z = truncf(position.z + AABB_SIZE.z - SMALLER);

  int start_x;
  int end_x;
  if(move.x > 0){
    start_x = max_x;
    end_x = truncf(position.x + AABB_SIZE.x + move.x - SMALLER);
  } else {
    start_x = min_x;
    end_x = truncf(position.x + move.x + SMALLER);
  }

  for( pos_x = start_x to end_x ){
    if(AnySolidVoxelsInArea(IntVector(pos_x, min_y, min_z), IntVector(pos_x, max_y, max_z))){
      // align to surface (EPSILON pushes the character slightly away from the wall)
      if(move.x > 0){
        position.x = pos_x - AABB_SIZE.x + SMALLER - EPSILON;
      } else {
        position.x = pos_x - SMALLER + EPSILON;
      }
      move.x = 0;
      break;
    }
  }
  position.x += move.x;
}

```

repeat for Y and Z.

Otherwise you'll need to build a huge collision map made up of continuously linked planes from the voxel grid and properly slide along those connected planes.
> 1 votes

---
Tags: c++, collision-resolution, voxels, aabb, collision-avoidance
---


# Question
Title: Best way to go about collision between rectangle and bool array containing pixel data?
Basically, if I have an array along the lines of

```
    bool[] collision;

```

Filled with a value for each pixel in the sprite I am checking collision against (pixel 1 = true, pixel 2 = false etc), how do I use it to check collision between the player and the texture?

```
      protected void GetCollisionData()
    {
    // Declare an array to hold the pixel data
        uint[] pixelLevelData = new uint[textureLevel.Width * textureLevel.Height];
        // Populate the array
        textureLevel.GetData(pixelLevelData, 0, textureLevel.Width * textureLevel.Height);

        for (int x = 0; x < textureLevel.Width; x++)
        {
            for (int y = 0; y < textureLevel.Height; y++)
            {
                 if (x < textureLevel.Width && x > 0 && y > 0 && y < textureLevel.Height)
                {
                    //If it's black, make a note that collision will happen
                    if (pixelLevelData[(x + y * textureLevel.Width)] == 4278190080)
                    {
                        collision[x + y * textureLevel.Width] = true;
                        debug = 9;
                    }
                    //else it's either something black already covers or transparent; no collision necessary
                    else
                        collision[x + y * textureLevel.Width] = false;
                }
            }
        }
    }

```

This is the relevant part that covers how I got my array of bools. How to I check collision between the set of bools and a normal rectangle?

# Answer
> 2 votes
What you are trying to do is called 'pixel perfect collision detection'. Both player and texture should be inside a rectangle. Everytime `Update` function is called you should check "broad collision" to see if the two rectangles intersect (there is a Rectangle.Intersects method in XNA for rectangles) . If they do intersect, we start checking "detailed collision". To do that you will have to check the intersection rectangle (the small area where the two rectangles collide) pixel per pixel, to see if each two pixels are both not black. If they are both not black, then there is an actual collision.
Useful link
More Useful link

**On a sidenote:** In most cases pixel per pixel collision detection is not needed and its really slow. Usually you use polygons/circles/rectangles/edges to check the collisions

In **physics engines,** there are classes and methods that can create those polygons/circles/rectangles/edges. **If those shapes are not enough,** there are also some algorithms inside physics engines (I have used Farseer Physics Engine with Monogame) which can create polygons from image "automatically" (depending on where the area is transparent or not usually), like Mark Bayazit's Algorithm. Every algorithm has differences, for example one can detect "holes" inside the texture, others can't.
Example:

When it comes to collision detection, you are better off using a **physics engine** or you will end up learning math/physics/trigonometry instead of programming and basically recreating a physics engine yourself.

Also, collision detection can be problematic if not done right. Let's say you have two objects that you want to check collision in every frame, a moving ball and a static thin wall. Unless you are moving the ball 1 pixel per frame, the following problems will happen:

* The ball will eventually end up being *inside* the wall at the frame when the collision is happening
* At really high ball speeds, the collision will never happen, because the ball will *pass right through* the wall, so the ball and the wall will never intersect (this is called *tunneling*)

---
Tags: c#, xna, 2d, collision-detection
---


# Question
Title: What is the difference between a Facebook Canvas and Facebook Web project?
I am making a game on cocos2d-JS for Facebook. What is the difference between Facebook Canvas & Facebook Web project. From what I can tell, Facebook Canvas ask for the secure url and Web ask for the site URL.

# Answer
> 2 votes
Facebook Canvas app are apps that live inside the facebook eco-system. This is done by Facebook creating an iFrame to the canvas URL you supply. The authentication system is a POST variable sent one time when the "Facebook APP" is opened.

Facebook Web project app are apps that access the Facebook API and do not leave in the Facebook eco-system. You would have to authenticate the user differently than with the POST method in the example of a Facebook App.

In the past I have created Facebook Web Projects using the same url as the Facebook Canvas URL in order to provide identical experience ( minus some style and menu changes ) for users coming to the site and users installing the Facebook app.

---
Tags: html-canvas, facebook, cocos2d-x-js
---


# Question
Title: How to make the BGM not stop between scenes?
I want my background music to keep playing on loop, but whenever I transition into another scene, the loop starts over.

Is there any way to have the scene record the last point of the music it plays, and in the next scene starts playing at that moment?

# Answer
> 3 votes
I managed to make it myself by making an Empty Object (BGM) where to place the music. Then, haivng a simple script attached to the object with the following code:

```
void Awake(){
     DontDestroyOnLoad(gameObject);
}

```

And it became a persistent object, therefore it's not destroyed between scenes.

---
Tags: unity, music
---


# Question
Title: How to handle realtime random movement with client side prediction
I'm building a realtime multiplayer game that runs the same 'physics' loop on client and server. I'm using a steering behavior 'wander' that is essential random movement. The client and server generate different Random numbers when running the wander algorithms.

I'm wondering how I can keep a naturally random looking movement but use some constant that will insure the client and server come to the same conclusion.

# Answer
You can use random seed. Select same 32-bit value in server and client (or server can send it to client at start). Use it as seed for random generator. You can send actual seed from server to client with game state update. If you don't want to send it you must be sure that client and server generates same number of random numbers by this random generator.

What you should know before you decided not send actual seed to client:

* You'll have problems with character culling on client (means don't process characters deep in a fog of war on client). If you want to make character culling best decision will be send all character state (with actual seed) from server to client when client should process character. So, server must decide when client should process character and when shouldn't. Be sure that you use separate random generators for each character.
* Same problem will be with AI lods.
* Random number from this random generator must be generated only in update with fixed time delta. If you want to use random digit for AI interpolation before render you should use separate random generator (there are no render on server, so don't care what seed you'll use).
* If you want to use different platforms for client and server (C++ and Java, for example), you must implement (or find) crossplatform random generator. That's not a big problem, because random generators easy to implement.
> 14 votes

# Answer
If both the server and client agree on the seed, most randomizing algorithm will output the same values.
> 3 votes

---
Tags: multiplayer, client-server, interpolation, movement-prediction
---